C# Network Programming - .e-bookshelf.de

Transcription

4176FM11/6/023:14 PMPage iC# NetworkProgramming Richard BlumSan Francisco London

4176FM11/6/023:14 PMPage viii

4176FM11/6/023:14 PMPage iC# NetworkProgramming Richard BlumSan Francisco London

4176FM11/6/023:14 PMPage iiAssociate Publisher: Joel FugazzottoAcquisitions Editor: Denise S. LincolnDevelopmental Editor: Carol HenryEditor: Sally EngelfriedProduction Editor: Erica YeeTechnical Editor: Dan FruminGraphic Illustrator: Jeff Wilson, Happenstance Type-O-RamaElectronic Publishing Specialists: Scott Benoit, Judy FungProofreaders: Emily Hsuan, Dave Nash, Laurie O’Connell, Yariv Rabinovitch, Nancy RiddioughIndexer: Ted LauxCover Designer:Carol Gorska, Gorska DesignCover Photographer: Carlos Navajas, The Image BankCopyright 2003 SYBEX Inc., 1151 Marina Village Parkway, Alameda, CA 94501. World rights reserved. No part of this publication maybe stored in a retrieval system, transmitted, or reproduced in any way, including but not limited to photocopy, photograph, magnetic, orother record, without the prior agreement and written permission of the publisher.Library of Congress Card Number: 2002111958ISBN: 0-7821-4176-5SYBEX and the SYBEX logo are either registered trademarks or trademarks of SYBEX Inc. in the United States and/or other countries.Screen reproductions produced with FullShot 99. FullShot 99 1991-1999 Inbit Incorporated. All rights reserved.FullShot is a trademark of Inbit Incorporated.Internet screen shot(s) using Microsoft Internet Explorer Version 6 reprinted by permission from Microsoft Corporation.TRADEMARKS: SYBEX has attempted throughout this book to distinguish proprietary trademarks from descriptive terms by followingthe capitalization style used by the manufacturer.The author and publisher have made their best efforts to prepare this book, and the content is based upon final release software wheneverpossible. Portions of the manuscript may be based upon pre-release versions supplied by software manufacturer(s). The author and the publisher make no representation or warranties of any kind with regard to the completeness or accuracy of the contents herein and accept noliability of any kind including but not limited to performance, merchantability, fitness for any particular purpose, or any losses or damagesof any kind caused or alleged to be caused directly or indirectly from this book.Manufactured in the United States of America10 9 8 7 6 5 4 3 2 1

4176FM11/6/023:14 PMPage iiiSOFTWARE LICENSE AGREEMENT: TERMSAND CONDITIONSThe media and/or any online materials accompanying this bookthat are available now or in the future contain programs and/ortext files (the “Software”) to be used in connection with the book.SYBEX hereby grants to you a license to use the Software, subjectto the terms that follow. Your purchase, acceptance, or use of theSoftware will constitute your acceptance of such terms.The Software compilation is the property of SYBEX unless otherwise indicated and is protected by copyright to SYBEX or othercopyright owner(s) as indicated in the media files (the “Owner(s)”).You are hereby granted a single-user license to use the Softwarefor your personal, noncommercial use only. You may not reproduce, sell, distribute, publish, circulate, or commercially exploitthe Software, or any portion thereof, without the written consentof SYBEX and the specific copyright owner(s) of any componentsoftware included on this media.In the event that the Software or components include specificlicense requirements or end-user agreements, statements ofcondition, disclaimers, limitations or warranties (“End-UserLicense”), those End-User Licenses supersede the terms andconditions herein as to that particular Software component. Yourpurchase, acceptance, or use of the Software will constitute youracceptance of such End-User Licenses.By purchase, use or acceptance of the Software you further agreeto comply with all export laws and regulations of the United Statesas such laws and regulations may exist from time to time.Reusable Code in This BookThe author(s) created reusable code in this publication expresslyfor reuse by readers. Sybex grants readers limited permission toreuse the code found in this publication, and available for download from our website so long as the author(s) are attributed inany application containing the reusable code and the code itself isnever distributed, posted online by electronic transmission, sold,or commercially exploited as a stand-alone product.Software SupportComponents of the supplemental Software and any offers associated with them may be supported by the specific Owner(s) of thatmaterial, but they are not supported by SYBEX. Informationregarding any available support may be obtained from the Owner(s)using the information provided in the appropriate read.me files orlisted elsewhere on the media.Should the manufacturer(s) or other Owner(s) cease to offer support or decline to honor any offer, SYBEX bears no responsibility.This notice concerning support for the Software is provided foryour information only. SYBEX is not the agent or principal of theOwner(s), and SYBEX is in no way responsible for providing anysupport for the Software, nor is it liable or responsible for any support provided, or not provided, by the Owner(s).DisclaimerSYBEX makes no warranty or representation, either expressed orimplied, with respect to the Software or its contents, quality, performance, merchantability, or fitness for a particular purpose. Inno event will SYBEX, its distributors, or dealers be liable to youor any other party for direct, indirect, special, incidental, consequential, or other damages arising out of the use of or inability touse the Software or its contents even if advised of the possibility ofsuch damage. In the event that the Software includes an onlineupdate feature, SYBEX further disclaims any obligation to providethis feature for any specific duration other than the initial posting.The exclusion of implied warranties is not permitted by somestates. Therefore, the above exclusion may not apply to you.This warranty provides you with specific legal rights; there maybe other rights that you may have that vary from state to state.The pricing of the book with the Software by SYBEX reflectsthe allocation of risk and limitations on liability contained in thisagreement of Terms and Conditions.Shareware DistributionThis Software may contain various programs that are distributed asshareware. Copyright laws apply to both shareware and ordinarycommercial software, and the copyright Owner(s) retains all rights. Ifyou try a shareware program and continue using it, you are expectedto register it. Individual programs differ on details of trial periods,registration, and payment. Please observe the requirements stated inappropriate files.Copy ProtectionThe Software in whole or in part may or may not be copy-protectedor encrypted. However, in all cases, reselling or redistributing thesefiles without authorization is expressly forbidden except as specifically provided for by the Owner(s) therein.

4176FM11/6/023:14 PMPage ivThis book is dedicated to Sister Marie Imelda,C.S.C, who in the late 1970s fought andstruggled to teach a bunch of goofy high schoolkids how to program. Thanks, Sister. “Trust inthe Lord with all your heart and lean not on yourown understanding; in all your ways acknowledgehim, and he will make your paths straight.”Prov. 3:5-6 (NIV)

4176FM11/6/023:14 PMPage vAcknowledgmentsFirst, all honor, glory, and praise goes to God, who through His Son, all things are possible,and who gives us the gift of eternal life.I would like to thank all the great people at Sybex for their help, guidance, and professionalism. Thanks to Denise Santoro Lincoln, the Acquisitions Editor, for offering me theopportunity to write this book. Also, thanks to Carol Henry, the Developmental Editor,for all her work guiding this book along and helping make my paragraphs make sense.Many thanks to Sally Engelfried, the Copy Editor, for turning my poor grammar intoperfect sentences, and to Dan Frumin, the Technical Editor, for going above and beyondthe call of duty fixing my programs and pointing out my technical blunders. Also, thanksto Carole McClendon at Waterside Productions for her help in arranging this book for me.Finally, I would like to thank my parents, Mike and Joyce Blum, for their dedication and support, and my wife Barbara and daughters Katie Jane and Jessica for their faith, love, and understanding, especially while I was writing this book.

4176FM11/6/023:14 PMPage viContents at a GlanceIntroductionPart IPart IIPart IIIxixNetwork Programming BasicsChapter 1:The C# LanguageChapter 2:IP Programming Basics41Chapter 3:C# Network Programming Classes87Chapter 4:DNS and C#3125Network Layer ProgramingChapter 5:Connection-Oriented Sockets167Chapter 6:Connectionless Sockets209Chapter 7:Using The C# Sockets Helper Classes249Chapter 8:Asynchronous Sockets291Chapter 9:Using Threads333Chapter 10:IP Multicasting375Application Layer Programming ExamplesChapter 11:ICMP411Chapter 12:SNMP441Chapter 13:SMTP477Chapter 14:HTTP511

4176FM11/6/023:14 PMPage viiChapter 15:Active Directory535Chapter 16:Remoting563Chapter 17:Security593Index623

4176FM11/6/023:14 PMPage viii

4176FM11/6/023:14 PMPage ixContentsIntroductionPart IChapter 1xixNetwork Programming Basics1The C# Language3Basics of .NETCommon Language Runtime (CLR)MSIL CodeInstalling a C# Development EnvironmentC# Development OptionsDownloading the .NET Framework SDKInstalling the .NET Framework SDKThe C# Runtime EnvironmentDownloading and Installing the C# Runtime PackageDeveloping with the C# RuntimeC# Programming BasicsCreating C# ProgramsCompiling and Running C# ProgramsUsing Multiple Source FilesDebugging C# ProgramsDebugging MSIL CodeC# FeaturesC# NamespacesUsing Strings in C# ProgramsC# StreamsC# Exception 33639

4176FM11/6/02x3:14 PMPage xContentsChapter 2Chapter 3Chapter 4IP Programming Basics41Watching Network TrafficInstalling the WinPcap ProgramsThe WinDump ProgramThe Analyzer ProgramAnalyzing Network PacketsThe Ethernet LayerThe IP LayerThe TCP LayerThe UDP LayerProgramming with TCP and UDPTCP Programming FeaturesUDP Programming FeaturesFinding IP Address InformationUsing ipconfigUsing the RegistryUsing WMIUsing DNSSummary424344485151566168697071727274808384C# Network Programming Classes87A Primer on Socket ProgrammingSocket Programming in WindowsC# Socket ProgrammingIP Addresses in C#Using C# SocketsC# Socket ExceptionsC# Socket Helper 103108119120120122123124DNS and C#125The Domain Name System (DNS)DNS StructureFinding a Hostname in DNS127127130

4176FM11/6/023:14 PMPage xiContentsPart IIChapter 5Chapter 6xiThe DNS DatabaseA Sample DNS DatabaseWindows DNS Client InformationDNS ConfigurationUsing C# to Investigate the DNS ConfigurationResolving Hostnames with nslookupDNS Classes in C#Synchronous MethodsAsynchronous k Layer Programing165Connection-Oriented Sockets167A Simple TCP ServerCreating the ServerTesting the ServerWatching the ServerA Simple TCP ClientCreating the ClientTesting the ClientWhen TCP Goes BadProblems with Data BuffersProblems with TCP MessagesSolving the TCP Message ProblemUsing C# Streams with TCPThe NetworkStream ClassThe StreamReader and StreamWriter 198202207Connectionless Sockets209A Simple UDP ApplicationThe UDP ServerA UDP ClientTesting the Client and Server ProgramsUsing Connect() in a UDP Client Example210211215217219

4176FM11/6/02xii3:14 PMPage xiiContentsChapter 7Chapter 8Distinguishing UDP MessagesWhen UDP Goes BadPreventing Lost DataPreventing Lost PacketsA Complete UDP ApplicationCatching Multiple Exceptions by Monitoring Error CodesThe Complete Client ProgramSummary220223223228242242245247Using The C# Sockets Helper Classes249The TcpClient ClassThe TcpClient Class ConstructorsThe TcpClient Class MethodsCreating a Simple Client ProgramTesting the ProgramThe TcpListener ClassThe TcpListener Class ConstructorsThe TcpListener Class MethodsA Simple Server ProgramIncorporating the StreamReader and StreamWriter ClassesThe UdpClient ClassThe UdpClient Class ConstructorsThe UdpClient Class MethodsUsing the UdpClient Class in ProgramsA Simple UdpClient Server ProgramA Simple UdpClient Client ProgramTesting the Sample ProgramsMoving Data across the NetworkMoving Binary DataCommunicating with Other Host TypesMoving Complex 260260262263264265265272280288Asynchronous Sockets291Windows Event ProgrammingUsing Events and Delegates292293

4176FM11/6/023:14 PMPage xiiiContentsChapter 9xiiiThe AsyncCallback ClassUsing Asynchronous SocketsEstablishing the ConnectionSending and Receiving DataSample Programs Using Asynchronous SocketsThe Client ProgramThe Server ProgramUsing Non-blocking Socket MethodsThe Poll() MethodThe Select() g Threads333How Applications Run in WindowsFinding Process Information Using C#ThreadsCreating Threads in a ProgramThe Thread ClassUsing the Thread ClassUsing Threads in a ServerCreating a Threaded ServerTesting the ServerWatching the ThreadsUsing Threads for Sending and Receiving DataThe TcpChat ProgramTesting the Chat Program and Watching the ThreadsThread PoolsThe ThreadPool ClassA Sample ThreadPool ProgramTesting the Program and Watching the ThreadsUsing Thread Pools in a ServerA ThreadPool ServerTesting the Program and Watching the 363364365366367369369371373

4176FM11/6/02xiv3:14 PMPage xivContentsChapter 10Part IIIChapter 11IP Multicasting375What Is Broadcasting?Local versus Global BroadcastsImplementing Broadcasting with C#Using Broadcast Packets to Advertise a ServerThe Advertising LoopWhat Is Multicasting?Multicast TechniquesSending Multicast Packets through RoutersC# IP Multicast SupportC# Socket MulticastingC# UdpClient MulticastingSample Multicast ApplicationTesting the Multicast Chat 405406Application Layer Programming Examples409ICMP411The ICMP ProtocolICMP Packet FormatICMP Packet TypesUsing Raw SocketsRaw Sockets FormatSending Raw PacketsReceiving Raw PacketsCreating an ICMP ClassThe ICMP Class ConstructorsThe ICMP Packet CreatorThe ICMP Checksum MethodPutting It All TogetherA Simple Ping ProgramTesting SimplePingAn Advanced Ping ProgramTesting 26431

4176FM11/6/023:14 PMPage xvContentsChapter 12Chapter 13xvThe TraceRoute.cs ProgramTesting TraceRoute.csThe FindMask ProgramThe Subnet Request PacketTesting anding SNMPSNMP CommandsCommunity NamesCommon Management Information BaseWorking with SNMP PacketsSNMP Packet FormatSNMP Packet LayoutSNMP CommunicationCreating a Simple SNMP ClassThe SNMP Class ProgramWalking through the ClassThe SimpleSNMP ProgramTesting the ProgramWatching the PacketsUsing Vendor MIBsThe Cisco CPU MIBThe CiscoRouter ProgramUsing GetNextRequest QueriesExtracting the Next MIBThe getnextMIB() MethodThe MAC Address ProgramTesting the 461462463463466469469470471473474SMTP477E-mail BasicsThe MTA Process478478

4176FM11/6/02xvi3:14 PMPage xviContentsChapter 14The MDA ProcessThe MUA ProcessSMTP and WindowsCollaboration Data Objects (CDO)SMTP Mail ServiceThe SmtpMail ClassClass Methods and PropertiesUsing the SmtpMail ClassUsing Expanded Mail Message FormatsThe RFC2822 Mail FormatThe MailMessage Class PropertiesUsing the MailMessage ClassMail AttachmentsuuencodeMIMEThe MailAttachment ClassA POP3 ClientThe POP3 ProtocolWriting a POP3 94495495499501501504510HTTP511The WebClient ClassDownloading Web DataViewing HTTP HeadersUploading Web DataUsing CredentialsAdvanced Web ClassesThe HttpWebRequest ClassThe HttpWebResponse ClassAdvanced Web Client ExampleWeb ServicesCreating the Web Service ServerTesting the Web ServiceCreating the Web Service ProxyCreating a C# Web Service 32533534

4176FM11/6/023:14 PMPage xviiContentsChapter 15Chapter 16xviiActive Directory535Network Directory BasicsThe LDAP SystemLDAP Objects and AttributesWorking with Active DirectoryParts of an Active DirectoryConnecting to an Active Directory ServerUsing C# to Access a Network DirectoryModifying Directory DataWorking with Object PropertiesWorking with ObjectsSearching the Network DirectoryStep 1: Defining the Search PropertiesStep 2: Retrieving the Search ResultsStep 3: Extracting the Search ResultsPerforming a SearchAdvanced Search 6557558558560561Remoting563Moving Data, RevisitedUsing a Serialization ClassProblems with SerializationAn Overview of RemotingThe Remote ClassThe Remoting ServerThe Communication ChannelThe Proxy ClassThe Client ProgramUsing RemotingCreating the Remote Class ProxyCreating the Server ProgramCreating the Client ProgramCreating a Proxy Class Using soapsudsViewing the Remote Class InterfacesThe soapsuds 583585585586590

4176FM11/6/02xviii3:14 PMPage xviiiContentsChapter 17IndexSecurity593Application Security: What’s Involved?Security PoliciesSecurity GroupsSecurity PermissionsSecurity ToolsSocket PermissionsImplementing Declarative SecurityUsing Declarative SecurityProtecting Network DataData EncryptionUsing Data EncryptionNetwork Data 615621623

4176FM11/6/023:14 PMPage xixIntroductionetworks (and network programming) have come a long way over the past 20 years. Inthe early days of network computing (the ’80s), network programming was left to theadvanced programmer, who typically built applications using the C programming languagein (mostly) Unix environments. Now, networks are everywhere, from large corporations tosmall home users. With so many computers connected together via networks, network-awareapplications are an accepted necessity. Existing applications must incorporate network featuresto stay competitive in the marketplace, and adding network communication to applications isessential. Network programs are used for everything from children’s games to advanced corporate database systems.NNetwork programming has always been a key feature of the Microsoft Windows operatingsystem. Unfortunately, you’ve had to know advanced C or C programming concepts to utilizethe network programming features in Windows programs. Now, though, the .NET Frameworklanguages simplify the task of adding network features to your applications. The .NET librariesprovide many network classes that can integrate network programming.As a network administrator, I’ve written many network programs using the C and Javalanguages for both Windows and Unix platforms. Today’s network management and securityrequirements make it essential to communicate with network devices and track workstationson the network. Trying to quickly write clean network code can be difficult when you areworking within the structure of the C socket APIs (especially in WinSock), and running Javaapplications is often a painful experience due to slow processing speeds and poor Windowssupport.The C# language has solved many of my network programming problems by allowing meto quickly prototype and deploy network applications using C# classes. Combining the C#Forms library to write the graphical code with the C# Socket library to write the networkingcode makes creating professional network applications simple. With C# network classes, whatused to take a day to write often only takes an hour or less.Who Should Read This BookObviously, if you are a C# programmer who is interested in creating network programs, thisbook is specifically intended to help you out. I’ve described each network C# class in detail, andyou’ll find lots of examples to help you implement the classes in your own work. If you havenever before written a network program, I’ve included useful explanations of the concepts andideas behind network programming in general, including common techniques for passing databetween network devices.

4176FM11/6/02xx3:14 PMPage xxIntroductionYou may already be familiar with writing network programs using other languages, such asC, C , or Java. In that case, you’ll be interested in seeing how easy it is to do this with the C#language.If you are new to the C# language, the first chapter describes the basics of creating andcompiling C# programs. You may want to skip other chapters in the first part of the book,which discuss network programming basics, and dive right into the C#-specific networkprogramming classes.How This Book Is OrganizedThis book is organized into four separate sections that cover a particular aspect of networkprogramming.Part I: Network Programming BasicsThe first four chapters are intended for programmers just starting out in network programmingand looking for some background information about how network programming works and thepieces that are required for network programming.Chapter 1, “The C# Language,” provides some basic information for the reader new to C#,such as which C# package to use for development work and how to compile C# programs.Chapter 2, “IP Programming Basics,” demonstrates how network programming has evolvedfrom the Unix world to the world of Windows, via the WinSock interface, and how .NET usesthe WinSock interface to access network resources.Chapter 3, “C# Network Programming Classes,” offers a quick introduction to the entireC# network libraries and shows the basic formats of the classes.Chapter 4, “DNS and C#,” rounds out the introductory section by showing network noviceshow DNS can resolve host addresses and how to use the C# DNS classes.Part II: Network Layer ProgrammingThe next group of chapters presents the core of network programming topics in the book.Each of these chapters discusses a major topic using in creating C# network programs.Chapter 5, “Connection-Oriented Sockets,” starts the discussion of network programmingby introducing stream programming using TCP. In addition to the standard C# Socket classused for stream programming, common pitfalls are discussed to help you create stream programs that will work on real networks.Chapter 6, “Connectionless Sockets,” discusses how to use the Socket class to create UDPapplications. In addition to showing you how to create UDP applications, this chapter alsodiscusses pitfalls related to UDP programming and shows examples of creating applicationsthat will withstand the problems inherent in real networks.

4176FM11/6/023:14 PMPage xxiIntroductionxxiChapter 7, “Using the C# Socket Helper Classes,” discusses the C# TcpClient, TcpListener,and UdpClient classes. These are special classes in .NET to help programmers create networkprograms with minimal effort. This chapter also discusses the basics of sending different datatypes across the network.Chapter 8, “Asynchronous Socket Programming,” discusses the technique of using asynchronous programming (prevalent in Windows programs) within the network programmingworld.Chapter 9, “Using Threads,” presents information for using multi-threaded applicationtechniques in network programs. This technology is often used in server applications thatmust service multiple clients at the same time.Chapter 10, “IP Multicasting,” describes how to use broadcasting and multicasting to sendpackets to multiple clients, cutting down on network bandwidth.Part III: Application Layer Programming ExamplesThe last part of the book describes specific network applications and how to implement themusing the C# network classes.Chapter 11, “ICMP,” shows how to use C# raw sockets to implement a protocol-specificapplication. The common ping and traceroute programs are shown within the C# networkprogramming context.Chapter 12, “SNMP,” describes how to write network management applications using C#.SNMP allows you to communicate with many devices on the network to retrieve networkstatistics. This chapter shows specific examples of reading a vendor MIB sheet and creating aC# application to extract the MIB data from the network device.Chapter 13, “SMTP,” describes the C# e-mail classes and shows examples of using them tosend mail using SMTP to remote mail servers. Also, an example of using other mail protocols(such as POP3) is shown.Chapter 14, “HTTP,” presents the C# web classes and how you can use them to createweb-enabled C# applications. Also, .NET web services , and how you can use them to hostyour application methods on an IIS server, are discussed.Chapter 15, “Active Directory,” shows the C# classes for contacting Microsoft ActiveDirectory servers. Examples are presented that show how to query, change, add, and deleteentries in the Active Directory.Chapter 16, “Remoting,” discusses the .NET concept of remoting, allowing an applicationto share methods with clients across the network. Examples are shown that demonstrate howto create both a remoting server and client.

4176FM11/6/02xxii3:14 PMPage xxiiIntroductionChapter 17, “Security,” closes out the book by describing how the .NET Frameworkhandles program security, and how you can implement security in your network applications using encryption techniques.Keeping Up to DateAll of the examples in this book have been created and compiled using the .NET Framework 1.0package. Each of the examples willeasily compile using any of the Microsoft Visual Studio packages (including Visual C#).At the time of this writing (2002) the current version of the .NET Framework wasversion 1.0, with Service Pack 1. Microsoft maintains the .NET Framework website athttp://www.microsoft.com/netframework, where all .NET announcements are posted.

4176ch01.qxd 10/13/04 3:13 PM Page 1Pa rt INetwork ProgrammingBasicsChapter 1: The C# LanguageChapter 2: IP Programming BasicsChapter 3: C# Network Programming ClassesChapter 4: DNS and C#

4176ch01.qxd 10/13/04 3:13 PM Page 2

4176ch01.qxd 10/13/04 3:13 PM Page 3Chapter 1The C# Language Basics of .NET Installing a C# development environment The C# runtime environment C# programming basics C# features

4176ch01.qxd 10/13/04 3:13 PM Page 44Chapter 1 The C# Languagen its short history, the Microsoft .NET technology has quickly become a popular programming platform for developing applications for Microsoft Windows workstations and servers.Although most of the media attention has focused around the web application capabilities of.NET, there are many other features that are useful to Windows programmers.IOne of those features is the new C# programming language, developed specifically for.NET. C# is becoming a widely used programming platform for programmers wanting tocreate both network-aware and stand-alone applications for Windows systems. The languageprovides many resources to help create robust Windows-based applications. Many programmers are migrating to the C# language to take advantage of these resources.Before learning the basics of network programming in C#, it is important that you understand the C# programming environment, the fundamentals of .NET, and how to create anddistribute C# applications. This chapter shows how to create a C# development environmenton your system and how to ensure that C# applications you create will run on other Windowsworkstations and servers. Finally, I’ll present a brief introduction to the C# language, alongwith some C# programming topics relevant to network programming. All together, the concepts presented in this chapter will help you get ready for C# network programming.Basics of .NETThe .NET group of programming languages differs from previous versions of Windowsprogramming languages in the way programs are created and run on the Windows systems.If you are not familiar with how C# programs operate, this section briefly describes the basicsyou should know to be able to deploy applications based on the .NET technologies.Common Language Runtime (CLR)The core of the Microsoft .NET technology is the Common Language Runtime (CLR) environment. This environment enables programmers to create programs using a multitude ofprogramming languages and run them on any platform that supports the CLR. The idea ofthe CLR is to provide a middle layer of Application Program Interfaces (APIs) that operatebetween the low-level Windows Win32 API functions and the application program code. Byproviding a common middle layer, Microsoft has given a larger number of application languages access to core Windows technologies (such as network support).The layout of how application programs run in the CLR environment is shown in Figure 1.1.High-level applications written in various .NET languages, such as Visual Basic .NET, VisualC .NET, Visual J# .NET, and of course Visual C# .NET, are compiled into a special intermediate language called Microsoft Intermediate Language (MSIL). The MSIL code is interpreted bythe CLR as the program runs; MSIL runs on the host operating system as a normal executable

4176ch01.qxd 10/13/04 3:13 PM Page 5Basics of .NET5program. Of course, legacy programs that do not use the CLR can still directly access the lowlevel Windows Win32 APIs as before.FIGURE 1.1:The CommonLanguage Runtime(CLR) environmentC .NETJ#.NETC#.NETVisual Basic.NETMicrosoft Intermediate LanguageCommon Language Runtime JIT compilerC Visual BasicJ Native compilersMicrosoft Win32 APIMicrosoft Windows Operating SystemThis CLR model also pertains to other operating systems. Because the CLR is ported toother operating systems, .NET programs will be able to run without recompiling them onthe new host systems. Currently, Microsoft supports the Shared Source Common LanguageInte

Part I Network Programming Basics. Chapter 1: The C# Language 3 Chapter 2: IP Programming Basics 41 Chapter 3: C# Network Programming Classes 87 Chapter 4: DNS and C# 125. Part II Network Layer Programing. Chapter 5: Connection-Oriented Sockets 167 Chapter 6: Connectionless Socke