C# Network Programming - download.e-bookshelf.de · Introduction xix. Part I Network Programming...

30
San Francisco • London C# Network Programming Richard Blum

Transcript of C# Network Programming - download.e-bookshelf.de · Introduction xix. Part I Network Programming...

  • San Francisco London

    C# NetworkProgramming

    Richard Blum

    4176FM 11/6/02 3:14 PM Page i

    File AttachmentC1.jpg

  • 4176FM 11/6/02 3:14 PM Page viii

  • San Francisco London

    C# NetworkProgramming

    Richard Blum

    4176FM 11/6/02 3:14 PM Page i

  • Associate 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 OConnell, Yariv Rabinovitch, Nancy RiddioughIndexer: Ted LauxCover Designer:Carol Gorska, Gorska DesignCover Photographer: Carlos Navajas, The Image Bank

    Copyright 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: 2002111958

    ISBN: 0-7821-4176-5

    SYBEX 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 pub-lisher 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 America

    10 9 8 7 6 5 4 3 2 1

    4176FM 11/6/02 3:14 PM Page ii

  • SOFTWARE 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 other-wise 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 repro-duce, 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 of condition, disclaimers, limitations or warranties (End-UserLicense), those End-User Licenses supersede the terms and conditions 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 down-load from our website so long as the author(s) are attributed in any 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 associ-ated 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 sup-port 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 sup-port 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, per-formance, merchantability, or fitness for a particular purpose. Inno event will SYBEX, its distributors, or dealers be liable to you or any other party for direct, indirect, special, incidental, conse-quential, 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 may be other rights that you may have that vary from state to state. The pricing of the book with the Software by SYBEX reflects the 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 specifi-cally provided for by the Owner(s) therein.

    4176FM 11/6/02 3:14 PM Page iii

  • This book is dedicated to Sister Marie Imelda,C.S.C, who in the late 1970s fought and

    struggled to teach a bunch of goofy high schoolkids how to program. Thanks, Sister. Trust in

    the Lord with all your heart and lean not on yourown understanding; in all your ways acknowledge

    him, and he will make your paths straight.Prov. 3:5-6 (NIV)

    4176FM 11/6/02 3:14 PM Page iv

  • Acknowledgments

    F irst, 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 profes-

    sionalism. 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, thanks to 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 sup-port, and my wife Barbara and daughters Katie Jane and Jessica for their faith, love, and under-standing, especially while I was writing this book.

    4176FM 11/6/02 3:14 PM Page v

  • Introduction xix

    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 Sockets 209

    Chapter 7: Using The C# Sockets Helper Classes 249

    Chapter 8: Asynchronous Sockets 291

    Chapter 9: Using Threads 333

    Chapter 10: IP Multicasting 375

    Part III Application Layer Programming Examples

    Chapter 11: ICMP 411

    Chapter 12: SNMP 441

    Chapter 13: SMTP 477

    Chapter 14: HTTP 511

    Contents at a Glance

    4176FM 11/6/02 3:14 PM Page vi

  • Chapter 15: Active Directory 535

    Chapter 16: Remoting 563

    Chapter 17: Security 593

    Index 623

    4176FM 11/6/02 3:14 PM Page vii

  • 4176FM 11/6/02 3:14 PM Page viii

  • Introduction xix

    Part I Network Programming Basics 1

    Chapter 1 The C# Language 3

    Basics of .NET 4Common Language Runtime (CLR) 4MSIL Code 5

    Installing a C# Development Environment 6C# Development Options 7Downloading the .NET Framework SDK 8Installing the .NET Framework SDK 9

    The C# Runtime Environment 10Downloading and Installing the C# Runtime Package 11Developing with the C# Runtime 11

    C# Programming Basics 12Creating C# Programs 12Compiling and Running C# Programs 15Using Multiple Source Files 16Debugging C# Programs 17Debugging MSIL Code 22

    C# Features 23C# Namespaces 24Using Strings in C# Programs 28C# Streams 33C# Exception Programming 36

    Summary 39

    Contents

    4176FM 11/6/02 3:14 PM Page ix

  • x

    Chapter 2 IP Programming Basics 41

    Watching Network Traffic 42Installing the WinPcap Programs 43The WinDump Program 44The Analyzer Program 48

    Analyzing Network Packets 51The Ethernet Layer 51The IP Layer 56The TCP Layer 61The UDP Layer 68

    Programming with TCP and UDP 69TCP Programming Features 70UDP Programming Features 71

    Finding IP Address Information 72Using ipconfig 72Using the Registry 74Using WMI 80Using DNS 83

    Summary 84

    Chapter 3 C# Network Programming Classes 87

    A Primer on Socket Programming 88Socket Programming in Windows 98

    C# Socket Programming 103IP Addresses in C# 103Using C# Sockets 108C# Socket Exceptions 119

    C# Socket Helper Classes 120TcpClient 120TcpListener 122UdpClient 123

    Summary 124

    Chapter 4 DNS and C# 125

    The Domain Name System (DNS) 127DNS Structure 127Finding a Hostname in DNS 130

    Contents

    4176FM 11/6/02 3:14 PM Page x

  • The DNS Database 131A Sample DNS Database 136

    Windows DNS Client Information 138DNS Configuration 138Using C# to Investigate the DNS Configuration 141Resolving Hostnames with nslookup 144

    DNS Classes in C# 153Synchronous Methods 153Asynchronous Methods 159

    Summary 164

    Part II Network Layer Programing 165

    Chapter 5 Connection-Oriented Sockets 167

    A Simple TCP Server 168Creating the Server 168Testing the Server 172Watching the Server 172

    A Simple TCP Client 173Creating the Client 174Testing the Client 176

    When TCP Goes Bad 177Problems with Data Buffers 177Problems with TCP Messages 180Solving the TCP Message Problem 184

    Using C# Streams with TCP 198The NetworkStream Class 198The StreamReader and StreamWriter Classes 202

    Summary 207

    Chapter 6 Connectionless Sockets 209

    A Simple UDP Application 210The UDP Server 211A UDP Client 215Testing the Client and Server Programs 217Using Connect() in a UDP Client Example 219

    Contents xi

    4176FM 11/6/02 3:14 PM Page xi

  • xii

    Distinguishing UDP Messages 220When UDP Goes Bad 223

    Preventing Lost Data 223Preventing Lost Packets 228

    A Complete UDP Application 242Catching Multiple Exceptions by Monitoring Error Codes 242The Complete Client Program 245

    Summary 247

    Chapter 7 Using The C# Sockets Helper Classes 249

    The TcpClient Class 250The TcpClient Class Constructors 250The TcpClient Class Methods 251Creating a Simple Client Program 252Testing the Program 254

    The TcpListener Class 255The TcpListener Class Constructors 255The TcpListener Class Methods 256A Simple Server Program 257Incorporating the StreamReader and StreamWriter Classes 258

    The UdpClient Class 259The UdpClient Class Constructors 259The UdpClient Class Methods 260Using the UdpClient Class in Programs 260A Simple UdpClient Server Program 262A Simple UdpClient Client Program 263Testing the Sample Programs 264

    Moving Data across the Network 265Moving Binary Data 265Communicating with Other Host Types 272Moving Complex Objects 280

    Summary 288

    Chapter 8 Asynchronous Sockets 291

    Windows Event Programming 292Using Events and Delegates 293

    Contents

    4176FM 11/6/02 3:14 PM Page xii

  • The AsyncCallback Class 297Using Asynchronous Sockets 298

    Establishing the Connection 298Sending and Receiving Data 301

    Sample Programs Using Asynchronous Sockets 304The Client Program 305The Server Program 312

    Using Non-blocking Socket Methods 319The Poll() Method 319The Select() Method 324

    Summary 331

    Chapter 9 Using Threads 333

    How Applications Run in Windows 334Finding Process Information Using C# 335Threads 343

    Creating Threads in a Program 350The Thread Class 350Using the Thread Class 351

    Using Threads in a Server 354Creating a Threaded Server 354Testing the Server 357Watching the Threads 357

    Using Threads for Sending and Receiving Data 358The TcpChat Program 359Testing the Chat Program and Watching the Threads 363

    Thread Pools 364The ThreadPool Class 365A Sample ThreadPool Program 366Testing the Program and Watching the Threads 367

    Using Thread Pools in a Server 369A ThreadPool Server 369Testing the Program and Watching the Threads 371

    Summary 373

    Contents xiii

    4176FM 11/6/02 3:14 PM Page xiii

  • xiv

    Chapter 10 IP Multicasting 375

    What Is Broadcasting? 376Local versus Global Broadcasts 376Implementing Broadcasting with C# 377

    Using Broadcast Packets to Advertise a Server 382The Advertising Loop 382

    What Is Multicasting? 390Multicast Techniques 391Sending Multicast Packets through Routers 392

    C# IP Multicast Support 393C# Socket Multicasting 394C# UdpClient Multicasting 399

    Sample Multicast Application 402Testing the Multicast Chat Program 405

    Summary 406

    Part III Application Layer Programming Examples 409

    Chapter 11 ICMP 411

    The ICMP Protocol 412ICMP Packet Format 412ICMP Packet Types 413

    Using Raw Sockets 415Raw Sockets Format 415Sending Raw Packets 416Receiving Raw Packets 417

    Creating an ICMP Class 417The ICMP Class Constructors 417The ICMP Packet Creator 420The ICMP Checksum Method 420Putting It All Together 422

    A Simple Ping Program 423Testing SimplePing 425

    An Advanced Ping Program 426Testing AdvPing 431

    Contents

    4176FM 11/6/02 3:14 PM Page xiv

  • The TraceRoute.cs Program 432Testing TraceRoute.cs 434

    The FindMask Program 435The Subnet Request Packet 435Testing FindMask.cs 437

    Summary 438

    Chapter 12 SNMP 441

    Understanding SNMP 442SNMP Commands 443Community Names 444Common Management Information Base 445

    Working with SNMP Packets 448SNMP Packet Format 448SNMP Packet Layout 450SNMP Communication 452

    Creating a Simple SNMP Class 452The SNMP Class Program 453Walking through the Class 455

    The SimpleSNMP Program 457Testing the Program 461Watching the Packets 462

    Using Vendor MIBs 463The Cisco CPU MIB 463The CiscoRouter Program 466

    Using GetNextRequest Queries 469Extracting the Next MIB 469The getnextMIB() Method 470The MAC Address Program 471Testing the Program 473

    Summary 474

    Chapter 13 SMTP 477

    E-mail Basics 478The MTA Process 478

    Contents xv

    4176FM 11/6/02 3:14 PM Page xv

  • xvi

    The MDA Process 480The MUA Process 481

    SMTP and Windows 483Collaboration Data Objects (CDO) 483SMTP Mail Service 484

    The SmtpMail Class 485Class Methods and Properties 486Using the SmtpMail Class 487

    Using Expanded Mail Message Formats 488The RFC2822 Mail Format 488The MailMessage Class Properties 491Using the MailMessage Class 493

    Mail Attachments 494uuencode 495MIME 495

    The MailAttachment Class 499A POP3 Client 501

    The POP3 Protocol 501Writing a POP3 Client 504

    Summary 510

    Chapter 14 HTTP 511

    The WebClient Class 512Downloading Web Data 512Viewing HTTP Headers 515Uploading Web Data 516Using Credentials 519

    Advanced Web Classes 521The HttpWebRequest Class 522The HttpWebResponse Class 523Advanced Web Client Example 525

    Web Services 528Creating the Web Service Server 529Testing the Web Service 531Creating the Web Service Proxy 532Creating a C# Web Service Client 533

    Summary 534

    Contents

    4176FM 11/6/02 3:14 PM Page xvi

  • Chapter 15 Active Directory 535

    Network Directory Basics 536The LDAP System 536LDAP Objects and Attributes 537

    Working with Active Directory 539Parts of an Active Directory 539Connecting to an Active Directory Server 543

    Using C# to Access a Network Directory 543Modifying Directory Data 546

    Working with Object Properties 546Working with Objects 550

    Searching the Network Directory 556Step 1: Defining the Search Properties 556Step 2: Retrieving the Search Results 557Step 3: Extracting the Search Results 558Performing a Search 558Advanced Search Features 560

    Summary 561

    Chapter 16 Remoting 563

    Moving Data, Revisited 564Using a Serialization Class 564Problems with Serialization 571

    An Overview of Remoting 574The Remote Class 575The Remoting Server 576The Communication Channel 577The Proxy Class 577The Client Program 577

    Using Remoting 578Creating the Remote Class Proxy 578Creating the Server Program 579Creating the Client Program 583

    Creating a Proxy Class Using soapsuds 585Viewing the Remote Class Interfaces 585The soapsuds Program 586

    Summary 590

    Contents xvii

    4176FM 11/6/02 3:14 PM Page xvii

  • xviii

    Chapter 17 Security 593

    Application Security: Whats Involved? 594Security Policies 594Security Groups 595Security Permissions 596Security Tools 597

    Socket Permissions 603Implementing Declarative Security 604Using Declarative Security 606

    Protecting Network Data 610Data Encryption 610Using Data Encryption 612Network Data Encryption 615

    Summary 621

    Index 623

    Contents

    4176FM 11/6/02 3:14 PM Page xviii

  • Introduction

    N etworks (and network programming) have come a long way over the past 20 years. In the 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 childrens games to advanced cor-porate database systems.

    Network programming has always been a key feature of the Microsoft Windows operatingsystem. Unfortunately, youve 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, Ive written many network programs using the C and Java languages for both Windows and Unix platforms. Todays 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. Ive described each network C# class in detail, andyoull find lots of examples to help you implement the classes in your own work. If you havenever before written a network program, Ive included useful explanations of the concepts andideas behind network programming in general, including common techniques for passing databetween network devices.

    4176FM 11/6/02 3:14 PM Page xix

  • xx Introduction

    You may already be familiar with writing network programs using other languages, such asC, C++, or Java. In that case, youll 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 network programming 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 pro-grams 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.

    4176FM 11/6/02 3:14 PM Page xx

  • xxi

    Chapter 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 asyn-chronous 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.

    Introduction

    4176FM 11/6/02 3:14 PM Page xxi

  • xxii

    Chapter 17, Security, closes out the book by describing how the .NET Frameworkhandles program security, and how you can implement security in your network applica-tions 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 pack-ages (including Visual C#).

    At the time of this writing (2002) the current version of the .NET Framework was version 1.0, with Service Pack 1. Microsoft maintains the .NET Framework website athttp://www.microsoft.com/netframework, where all .NET announcements are posted.

    Introduction

    4176FM 11/6/02 3:14 PM Page xxii

  • Part I

    Network ProgrammingBasics

    Chapter 1: The C# Language

    Chapter 2: IP Programming Basics

    Chapter 3: C# Network Programming Classes

    Chapter 4: DNS and C#

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

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

  • The C# Language

    Basics of .NET

    Installing a C# development environment

    The C# runtime environment

    C# programming basics

    C# features

    Chapter 1

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

  • 4

    I n its short history, the Microsoft .NET technology has quickly become a popular program-ming 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.

    One 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 program-mers 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 under-stand 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, Ill present a brief introduction to the C# language, alongwith some C# programming topics relevant to network programming. All together, the con-cepts 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 Windows programming 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) envi-ronment. 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 lan-guages 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 interme-diate 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

    Chapter 1 The C# Language

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

  • 5

    program. Of course, legacy programs that do not use the CLR can still directly access the low-level Windows Win32 APIs as before.

    This 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 LanguageInterface (CLI) project (nicknamed Rotor), which ports the CLR environment to theFreeBSD operating system. It is expected that the Rotor project will branch out to otheroperating systems as well. At the time of this writing you can get more information aboutRotor at the following website:

    http://msdn.microsoft.com/downloads/default.asp?URL=/downloads/sample.asp?url=/msdn-files/027/001/901/msdncompositedoc.xml

    For programs to run in the CLR, they must be compiled into the special MSIL format.The .NET C# compiler is used to convert C# language programs to MSIL code that runs in the CLR environment. The next section describes the MSIL code.

    MSIL CodeWhen you compile a C# program, it produces an executable file. However, this executablefile is different from the ones you may be used to seeing produced from other Windowscompilers. Instead of a low-level assembly program that can run directly in Windows, thisexecutable file contains two parts:

    A stub assembly language program to start the CLR compiler

    The MSIL code of the compiled application

    The stub program starts the CLR just-in-time (JIT) compiler, which compiles the MSILprogram code to native Win32 code that can be run on the system. Unlike native Windows

    J++

    Microsoft Windows Operating System

    Microsoft Win32 API

    Common Language Runtime JIT compiler Native compilers

    C++Visual BasicMicrosoft Intermediate Language

    C++.NET C#.NETJ#.NET Visual Basic.NET

    F I G U R E 1 . 1 :The Common Language Runtime(CLR) environment

    Basics of .NET

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

  • 6

    applications, which interact directly with the low-level Win32 API system, .NET applicationsrely on the .NET Framework CLR to run. Running a .NET application on a system thatdoes not have the .NET Framework installed will produce an error message like the one inFigure 1.2. The .NET Framework is crucial to any .NET application, whether it is runningon a Windows workstation or server. Without it the MSIL code cannot run. Any Windowsworkstation or server expected to run .NET programs must have the .NET Frameworkinstalled.

    Microsoft is committed to ensuring the .NET Framework will be installed on all futureversions of the Windows OS. However, older versions of Windows must have the .NETFramework manually installed. The following section includes instructions for installing the .NET Framework for a developer environment to allow you to create, compile, and run.NET applications.

    Installing a C# Development EnvironmentBefore you can begin programming in C#, you must have a C# development environmentasystem for creating, compiling, and debugging C# programs. Unfortunately, one of the moststringent requirements for .NET application development is the designation of OS platformto use for development. Currently, .NET requires one of the following systems for full C#program development:

    Windows NT 4 Workstation or Server (with Service Pack 6a)

    Windows 2000 Professional or Server (with Service Pack 2)

    Windows XP Home Edition or Professional

    Programmers without access to any of these systems will not be able to develop C# programsbut there is a solution to this, as will be explained later in the C# Runtime Environment section.

    F I G U R E 1 . 2 :Trying to run a .NETapplication withoutthe .NET Framework

    Chapter 1 The C# Language

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