C# Network Programming By Richard Blum ISBN:0782141765

Transcription

This document is created with the unregistered version of CHM2PDF PilotC# Network Programmingby Richard BlumSybex 2003 (647 pages)ISBN:0782141765This book helps newcomers get started with a look at the basics of network programming as theyrelate to C#, including the language s network classes, the Winsock interface, and DNSresolution.Table of ContentsC# Network ProgrammingIntroductionPart I - Network Programming BasicsChapt- The C# Languageer1Chapt- IP Programming Basicser2Chapt- C# Network Programming Classeser3Chapt- DNS and C#er4Part II - Network Layer ProgramingChapt- Connection-Oriented Socketser5Chapt- Connectionless Socketser6Chapt- Using The C# Sockets Helper Classeser7Chapt- Asynchronous Socketser8Chapt- Using Threadser9

This document is created with the unregistered version of CHM2PDF PilotChapt- IP Multicastinger10Part III - Application Layer Programming ExamplesChapt- ICMPer11Chapt- SNMPer12Chapt- SMTPer13Chapt- HTTPer14Chapt- Active Directoryer15Chapt- Remotinger16Chapt- Securityer17IndexList of FiguresList of TablesList of ListingsList of Sidebars

This document is created with the unregistered version of CHM2PDF PilotBack CoverOn its own, C# simplifies network programming. Combine it with the precise instruction found in C# NetworkProgramming, and you ll find that building network applications is easier and quicker than ever.This book helps newcomers get started with a look at the basics of network programming as they relate to C#,including the language s network classes, the Winsock interface, and DNS resolution. Spend as much time here asyou need, then dig into the core topics of the network layer. You ll learn to make sockets connections via TCP, andconnectionless connections via UDP. You ll also discover just how much help C# gives you with some of yourtoughest chores, such as asynchronous socket programming, multithreading, and multicasting.Network-layer techniques are just a means to an end, of course, and so this book keeps going, providing a series ofdetailed application-layer programming examples that show you how to work with real protocols and real networkenvironments to build and implement a variety of applications. Use SNMP to manage network devices, SMTP tocommunicate with remote mail servers, and HTTP to Web-enable your applications. And use classes native to C#to query and modify Active Directory entries.Rounding it all out is plenty of advanced coverage to push your C# network programming skills to the limit. Forexample, you ll learn two ways to share application methods across the network: using Web services and remoting.You ll also master the security features intrinsic to C# and .NET features that stand to benefit all of yourprogramming projects.About the AuthorRichard Blum has spent 14 years as a network and system administrator for the US Department of Defense,supporting a large network of workstations and servers. He holds a BS in Electrical Engineering and an MS inManagement Information Systems, both from Purdue University.

This document is created with the unregistered version of CHM2PDF PilotC# Network ProgrammingRichard BlumAssociate 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. Nopart of this publication may be stored in a retrieval system, transmitted, or reproduced in any way, including but notlimited to photocopy, photograph, magnetic, or other record, without the prior agreement and written permission ofthe 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 Statesand/or other countries.Screen reproductions produced with FullShot 99. FullShot 99 1991-1999 Inbit Incorporated. All rightsreserved.FullShot is a trademark of Inbit Incorporated.Internet screen shot(s) using Microsoft Internet Explorer Version 6 reprinted by permission from MicrosoftCorporation.TRADEMARKS: SYBEX has attempted throughout this book to distinguish proprietary trademarks fromdescriptive terms by following the 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 finalrelease software whenever possible. Portions of the manuscript may be based upon pre-release versions supplied by

This document is created with the unregistered version of CHM2PDF Pilotsoftware manufacturer(s). The author and the publisher make no representation or warranties of any kind with regardto the completeness or accuracy of the contents herein and accept no liability of any kind including but not limited toperformance, merchantability, fitness for any particular purpose, or any losses or damages of any kind caused oralleged to be caused directly or indirectly from this book.Manufactured in the United States of America10 9 8 7 6 5 4 3 2 1Software License Agreement: Terms and ConditionsThe media and/or any online materials accompanying this book that are available now or in the future containprograms and/or text files (the Software ) to be used in connection with the book. SYBEX hereby grants to you alicense to use the Software, subject to the terms that follow. Your purchase, acceptance, or use of the Software willconstitute your acceptance of such terms.The Software compilation is the property of SYBEX unless otherwise indicated and is protected by copyright toSYBEX or other copyright owner(s) as indicated in the media files (the Owner(s) ). You are hereby granted asingle-user license to use the Software for your personal, noncommercial use only. You may not reproduce, sell,distribute, publish, circulate, or commercially exploit the Software, or any portion thereof, without the written consentof SYBEX and the specific copyright owner(s) of any component software included on this media.In the event that the Software or components include specific license requirements or end-user agreements,statements of condition, disclaimers, limitations or warranties ( End-User License ), those End-User Licensessupersede the terms and conditions herein as to that particular Software component. Your purchase, acceptance, oruse of the Software will constitute your acceptance of such End-User Licenses.By purchase, use or acceptance of the Software you further agree to comply with all export laws and regulations ofthe United States as such laws and regulations may exist from time to time.Reusable Code in This BookThe author(s) created reusable code in this publication expressly for reuse by readers. Sybex grants readers limitedpermission to reuse the code found in this publication, and available for download from our website so long as theauthor(s) are attributed in any application containing the reusable code and the code itself is never distributed, postedonline 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 specificOwner(s) of that material, but they are not supported by SYBEX. Information regarding any available support maybe obtained from the Owner(s) using the information provided in the appropriate read.me files or listed elsewhere onthe media.Should the manufacturer(s) or other Owner(s) cease to offer support or decline to honor any offer, SYBEX bears noresponsibility. This notice concerning support for the Software is provided for your information only. SYBEX is not

This document is created with the unregistered version of CHM2PDF Pilotthe agent or principal of the Owner(s), and SYBEX is in no way responsible for providing any support for theSoftware, 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 or implied, with respect to the Software or itscontents, quality, performance, merchantability, or fitness for a particular purpose. In no event will SYBEX, itsdistributors, or dealers be liable to you or any other party for direct, indirect, special, incidental, consequential, orother damages arising out of the use of or inability to use the Software or its contents even if advised of the possibilityof such damage. In the event that the Software includes an online update feature, SYBEX further disclaims anyobligation to provide this feature for any specific duration other than the initial posting.The exclusion of implied warranties is not permitted by some states. Therefore, the above exclusion may not apply toyou. This warranty provides you with specific legal rights; there may be other rights that you may have that vary fromstate to state. The pricing of the book with the Software by SYBEX reflects the allocation of risk and limitations onliability contained in this agreement of Terms and Conditions.Shareware DistributionThis Software may contain various programs that are distributed as shareware. Copyright laws apply to bothshareware and ordinary commercial software, and the copyright Owner(s) retains all rights. If you try a sharewareprogram and continue using it, you are expected to register it. Individual programs differ on details of trial periods,registration, and payment. Please observe the requirements stated in appropriate files.Copy ProtectionThe Software in whole or in part may or may not be copy-protected or encrypted. However, in all cases, reselling orredistributing these files without authorization is expressly forbidden except as specifically provided for by theOwner(s) therein.This book is dedicated to Sister Marie Imelda, C.S.C, who in the late 1970s fought and struggled to teach abunch of goofy high school kids how to program. Thanks, Sister. Trust in the Lord with all your heart andlean not on your own understanding; in all your ways acknowledge him, and he will make your pathsstraight. Prov. 3:5-6 (NIV)AcknowledgmentsFirst, all honor, glory, and praise goes to God, who through His Son, all things are possible, and who gives us the giftof eternal life.I would like to thank all the great people at Sybex for their help, guidance, and professionalism. Thanks to DeniseSantoro Lincoln, the Acquisitions Editor, for offering me the opportunity to write this book. Also, thanks to CarolHenry, the Developmental Editor, for all her work guiding this book along and helping make my paragraphs makesense.Many thanks to Sally Engelfried, the Copy Editor, for turning my poor grammar into perfect sentences, and to DanFrumin, the Technical Editor, for going above and beyond the call of duty fixing my programs and pointing out mytechnical blunders. Also, thanks to Carole McClendon at Waterside Productions for her help in arranging this book

This document is created with the unregistered version of CHM2PDF Pilotfor me.Finally, I would like to thank my parents, Mike and Joyce Blum, for their dedication and support, and my wifeBarbara and daughters Katie Jane and Jessica for their faith, love, and understanding, especially while I was writingthis book.The quotation on the bottom of the front cover is taken from the sixty-third chapter of Lao Tzu s Tao TeChing, the classic work of Taoist philosophy. This particular verse is from the translation by D. C. Lau(copyright 1963) and communicates the idea that one should confront the difficult while it is still easy andaccomplish a great task by a series of small acts.It is traditionally held that Lao Tzu lived in the fifth century B.C. in China, during the Chou dynasty, but it isunclear whether he was actually a historical figure. It is said that he was a teacher of Confucius. Theconcepts embodied in the Tao Te Ching influenced religious thinking in the Far East, including Zen Buddhismin Japan. Many in the West, however, have wrongly understood the Tao Te Ching to be primarily a mysticalwork; in fact, much of the advice in the book is grounded in a practical moral philosophy governing personalconduct.

This document is created with the unregistered version of CHM2PDF PilotIntroductionNetworks (and network programming) have come a long way over the past 20 years. In the early days of networkcomputing (the 80s), network programming was left to the advanced programmer, who typically built applicationsusing the C programming language in (mostly) Unix environments. Now, networks are everywhere, from largecorporations to small home users. With so many computers connected together via networks, network-awareapplications are an accepted necessity. Existing applications must incorporate network features to stay competitive inthe marketplace, and adding network communication to applications is essential. Network programs are used foreverything from children s games to advanced corporate database systems.Network programming has always been a key feature of the Microsoft Windows operating system. Unfortunately,you ve had to know advanced C or C programming concepts to utilize the network programming features inWindows programs. Now, though, the .NET Framework languages simplify the task of adding network features toyour applications. The .NET libraries provide many network classes that can integrate network programming.As a network administrator, I ve written many network programs using the C and Java languages for both Windowsand Unix platforms. Today s network management and security requirements make it essential to communicate withnetwork devices and track workstations on the network. Trying to quickly write clean network code can be difficultwhen you are working 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 Windows support.The C# language has solved many of my network programming problems by allowing me to quickly prototype anddeploy network applications using C# classes. Combining the C# Forms library to write the graphical code with theC# Socket library to write the networking code makes creating professional network applications simple. With C#network classes, what used 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, this book is specificallyintended to help you out. I ve described each network C# class in detail, and you ll find lots of examples to help youimplement the classes in your own work. If you have never before written a network program, I ve included usefulexplanations of the concepts and ideas behind network programming in general, including common techniques forpassing data between network devices.You may already be familiar with writing network programs using other languages, such as C, C , or Java. In thatcase, 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 and compiling C# programs. Youmay want to skip other chapters in the first part of the book, which discuss network programming basics, and diveright into the C#-specific network programming classes.

This document is created with the unregistered version of CHM2PDF Pilot

This document is created with the unregistered version of CHM2PDF PilotHow This Book Is OrganizedThis book is organized into four separate sections that cover a particular aspect of network programming.Part I: Network Programming BasicsThe first four chapters are intended for programmers just starting out in network programming and looking for somebackground information about how network programming works and the pieces that are required for networkprogramming.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 evolved from the Unix world tothe world of Windows, via the WinSock interface, and how .NET uses the WinSock interface to access networkresources.Chapter 3, C# Network Programming Classes, offers a quick introduction to the entire C# network libraries andshows the basic formats of the classes.Chapter 4, DNS and C#, rounds out the introductory section by showing network novices how DNS can resolvehost 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 chaptersdiscusses a major topic using in creating C# network programs.Chapter 5, Connection-Oriented Sockets, starts the discussion of network programming by introducing streamprogramming using TCP. In addition to the standard C# Socket class used for stream programming, common pitfallsare 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 UDP applications. In additionto showing you how to create UDP applications, this chapter also discusses pitfalls related to UDP programming andshows examples of creating applications that will withstand the problems inherent in real networks.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 network programs with minimal effort. This chapteralso discusses the basics of sending different data types across the network.

This document is created with the unregistered version of CHM2PDF PilotChapter 8, Asynchronous Socket Programming, discusses the technique of using asynchronous programming(prevalent in Windows programs) within the network programming world.Chapter 9, Using Threads, presents information for using multi-threaded application techniques in networkprograms. This technology is often used in server applications that must service multiple clients at the same time.Chapter 10, IP Multicasting, describes how to use broadcasting and multicasting to send packets to multiple clients,cutting down on network bandwidth.

This document is created with the unregistered version of CHM2PDF PilotPart III: Application Layer ProgrammingExamplesThe last part of the book describes specific network applications and how to implement them using the C# networkclasses.Chapter 11, ICMP, shows how to use C# raw sockets to implement a protocol-specific application. The commonping and traceroute programs are shown within the C# network programming context.Chapter 12, SNMP, describes how to write network management applications using C#. SNMP allows you tocommunicate with many devices on the network to retrieve network statistics. This chapter shows specific examplesof reading a vendor MIB sheet and creating a C# 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 to send mail using SMTP toremote 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 create web-enabled C#applications. Also, .NET web services , and how you can use them to host your application methods on an IISserver, are discussed.Chapter 15, Active Directory, shows the C# classes for contacting Microsoft Active Directory servers. Examplesare presented that show how to query, change, add, and delete entries in the Active Directory.Chapter 16, Remoting, discusses the .NET concept of remoting, allowing an application to share methods withclients across the network. Examples are shown that demonstrate how to create both a remoting server and client.Chapter 17, Security, closes out the book by describing how the .NET Framework handles program security, andhow you can implement security in your network applications using encryption techniques.

This document is created with the unregistered version of CHM2PDF PilotPart II: Network Layer ProgrammingThe next group of chapters presents the core of network programming topics in the book. Each of these chaptersdiscusses a major topic using in creating C# network programs.Chapter 5, Connection-Oriented Sockets, starts the discussion of network programming by introducing streamprogramming using TCP. In addition to the standard C# Socket class used for stream programming, common pitfallsare 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 UDP applications. In additionto showing you how to create UDP applications, this chapter also discusses pitfalls related to UDP programming andshows examples of creating applications that will withstand the problems inherent in real networks.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 network programs with minimal effort. This chapteralso discusses the basics of sending different data types across the network.Chapter 8, Asynchronous Socket Programming, discusses the technique of using asynchronous programming(prevalent in Windows programs) within the network programming world.Chapter 9, Using Threads, presents information for using multi-threaded application techniques in networkprograms. This technology is often used in server applications that must service multiple clients at the same time.Chapter 10, IP Multicasting, describes how to use broadcasting and multicasting to send packets to multiple clients,cutting down on network bandwidth.

This document is created with the unregistered version of CHM2PDF PilotPart III: Application Layer ProgrammingExamplesThe last part of the book describes specific network applications and how to implement them using the C# networkclasses.Chapter 11, ICMP, shows how to use C# raw sockets to implement a protocol-specific application. The commonping and traceroute programs are shown within the C# network programming context.Chapter 12, SNMP, describes how to write network management applications using C#. SNMP allows you tocommunicate with many devices on the network to retrieve network statistics. This chapter shows specific examplesof reading a vendor MIB sheet and creating a C# 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 to send mail using SMTP toremote 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 create web-enabled C#applications. Also, .NET web services , and how you can use them to host your application methods on an IISserver, are discussed.Chapter 15, Active Directory, shows the C# classes for contacting Microsoft Active Directory servers. Examplesare presented that show how to query, change, add, and delete entries in the Active Directory.Chapter 16, Remoting, discusses the .NET concept of remoting, allowing an application to share methods withclients across the network. Examples are shown that demonstrate how to create both a remoting server and client.Chapter 17, Security, closes out the book by describing how the .NET Framework handles program security, andhow you can implement security in your network applications using encryption techniques.

This document is created with the unregistered version of CHM2PDF PilotKeeping Up to DateAll of the examples in this book have been created and compiled using the .NET Framework 1.0 package. Each ofthe 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 was version 1.0, with Service Pack 1.Microsoft maintains the .NET Framework website at http://www.microsoft.com/netframework, where all .NETannouncements are posted.

This document is created with the unregistered version of CHM2PDF PilotPart I: Network ProgrammingBasicsChapter ListChapter 1: The C# Language Chapter 2: IP Programming Basics Chapter 3: C# Network Programming ClassesChapter 4: DNS and C#

This document is created with the unregistered version of CHM2PDF PilotChapter 1: The C# LanguageOverviewIn its short history, the Microsoft .NET technology has quickly become a popular programming platform fordeveloping applications for Microsoft Windows workstations and servers. Although most of the media attention hasfocused around the web application capabilities of .NET, there are many other features that are useful to Windowsprogrammers.One of those features is the new C# programming language, developed specifically for .NET. C# is becoming awidely used programming platform for programmers wanting to create both network-aware and stand-aloneapplications for Windows systems. The language provides many resources to help create robust Windows-basedapplications. 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# programmingenvironment, the fundamentals of .NET, and how to create and distribute C# applications. This chapter shows howto create a C# development environment on your system and how to ensure that C# applications you create will runon other Windows workstations and servers. Finally, I ll present a brief introduction to the C# language, along withsome C# programming topics relevant to network programming. All together, the concepts presented in this chapterwill help you get ready for C# network programming.

This document is created with the unregistered version of CHM2PDF PilotBasics of .NETThe .NET group of programming languages differs from previous versions of Windows programming languages in theway programs are created and run on the Windows systems. If you are not familiar with how C# programs operate,this section briefly describes the basics you should know to be able to deploy applications based on the .NETtechnologies.Common Language Runtime (CLR)The core of the Microsoft .NET technology is the Common Language Runtime (CLR) environment. Thisenvironment enables programmers to create programs using a multitude of programming languages and run them onany platform that supports the CLR. The idea of the CLR is to provide a middle layer of Application ProgramInterfaces (APIs) that operate between the low-level Windows Win32 API functions and the application programcode. By providing a common middle layer, Microsoft has given a larger number of application languages access tocore 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 applicationswritten in various .NET languages, such as Visual Basic .NET, Visual C .NET, Visual J# .NET, and of courseVisual C# .NET, are compiled into a special intermediate language called Microsoft Intermediate Language (MSIL). The MSIL code is interpreted by the CLR as the program runs; MSIL runs on the host operating system as anormal executable program. Of course, legacy programs that do not use the CLR can still directly access thelow-level Windows Win32 APIs as before.Figure 1.1: The Common Language Runtime (CLR) environmentThis CLR model also pertains to other operating systems. Because the CLR is ported to other operating systems,.NET programs will be able to run without recompiling them on the new host systems. Currently, Microsoft supportsthe Shared Source Common Language Interface (CLI) project (nicknamed Rotor), which ports the CLRenvironment to the FreeBSD 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 about Rotor at the ds/default.asp?URL /downloads/sample.asp?url /msdn-files/027/001/901/msdncompositedoc.xmlFor programs to run in the CLR, they must be compiled into the special MSIL format. The .NET C# compiler isused to convert C# language programs to MSIL code that runs in the CLR environment. The next section describesthe MSIL code.

This document is created with the unregistered version of CHM2PDF PilotMSIL CodeWhen you compile a C# program, it produces an executable file. However, this executable file is different from theones you may be used to seeing produced from other Windows compilers. Instead of a low-level assembly programthat can run directly in Windows, this executable file contains two parts: A stub assembly language program to start the CLR compiler The MSIL code of the compiled applicationThe stub program starts the CLR just-in-time (JIT) compiler, which compiles the MSIL program code to nativeWin32 code that can be run on the system. Unlike native Windows applications, which interact directly with thelow-level Win32 API system, .NET applications rely on the .NET Framework CLR to run. Running a .NETapplication on a system that does not have the .NET Framework installed will produce an error message like the onein Figure 1.2. The .NET Framework is crucial to any .NET application, whether it is running on a Windowsworkstation or server. Without it the MSIL code cannot run. Any Windows workstation or server expected to run.NET prog

This book helps newcomers get started with a look at the basics of network programming as they relate to C#, including the language s network classes, the Winsock interface, and DNS resolution. Table of Contents C# Network Programming Introduction Part I - Network Programming Basics Ch ap