0% found this document useful (0 votes)
154 views15 pages

C# Netwotk

mask.wtc

Uploaded by

Ali Al-Hamdani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
154 views15 pages

C# Netwotk

mask.wtc

Uploaded by

Ali Al-Hamdani
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 15

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

C# Network

Programming
Richard Blum

San Francisco • London


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

C# Network

Programming
Richard Blum

San Francisco • London


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

Associate Publisher: Joel Fugazzotto


Acquisitions Editor: Denise S. Lincoln
Developmental Editor: Carol Henry
Editor: Sally Engelfried
Production Editor: Erica Yee
Technical Editor: Dan Frumin
Graphic Illustrator: Jeff Wilson, Happenstance Type-O-Rama
Electronic Publishing Specialists: Scott Benoit, Judy Fung
Proofreaders: Emily Hsuan, Dave Nash, Laurie O’Connell, Yariv Rabinovitch, Nancy Riddiough
Indexer: Ted Laux
Cover Designer:Carol Gorska, Gorska Design
Cover 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 may
be stored in a retrieval system, transmitted, or reproduced in any way, including but not limited to photocopy, photograph, magnetic, or
other 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 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 final release software whenever
possible. 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 no
liability of any kind including but not limited to performance, merchantability, fitness for any particular purpose, or any losses or damages
of 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 iii

SOFTWARE LICENSE AGREEMENT: TERMS using the information provided in the appropriate read.me files or
AND CONDITIONS listed elsewhere on the media.
The media and/or any online materials accompanying this book
Should the manufacturer(s) or other Owner(s) cease to offer sup-
that are available now or in the future contain programs and/or
port or decline to honor any offer, SYBEX bears no responsibility.
text files (the “Software”) to be used in connection with the book.
This notice concerning support for the Software is provided for
SYBEX hereby grants to you a license to use the Software, subject
your information only. SYBEX is not the agent or principal of the
to the terms that follow. Your purchase, acceptance, or use of the
Owner(s), and SYBEX is in no way responsible for providing any
Software will constitute your acceptance of such terms.
support for the Software, nor is it liable or responsible for any sup-
port provided, or not provided, by the Owner(s).
The Software compilation is the property of SYBEX unless other-
wise indicated and is protected by copyright to SYBEX or other
Disclaimer
copyright owner(s) as indicated in the media files (the “Owner(s)”).
SYBEX makes no warranty or representation, either expressed or
You are hereby granted a single-user license to use the Software
implied, with respect to the Software or its contents, quality, per-
for your personal, noncommercial use only. You may not repro-
formance, merchantability, or fitness for a particular purpose. In
duce, sell, distribute, publish, circulate, or commercially exploit
no event will SYBEX, its distributors, or dealers be liable to you
the Software, or any portion thereof, without the written consent
or any other party for direct, indirect, special, incidental, conse-
of SYBEX and the specific copyright owner(s) of any component
quential, or other damages arising out of the use of or inability to
software included on this media.
use the Software or its contents even if advised of the possibility of
such damage. In the event that the Software includes an online
In the event that the Software or components include specific
update feature, SYBEX further disclaims any obligation to provide
license requirements or end-user agreements, statements of
this feature for any specific duration other than the initial posting.
condition, disclaimers, limitations or warranties (“End-User
License”), those End-User Licenses supersede the terms and
The exclusion of implied warranties is not permitted by some
conditions herein as to that particular Software component. Your
states. Therefore, the above exclusion may not apply to you.
purchase, acceptance, or use of the Software will constitute your
This warranty provides you with specific legal rights; there may
acceptance of such End-User Licenses.
be other rights that you may have that vary from state to state.
The pricing of the book with the Software by SYBEX reflects
By purchase, use or acceptance of the Software you further agree
the allocation of risk and limitations on liability contained in this
to comply with all export laws and regulations of the United States
agreement of Terms and Conditions.
as such laws and regulations may exist from time to time.
Shareware Distribution
Reusable Code in This Book
This Software may contain various programs that are distributed as
The author(s) created reusable code in this publication expressly
shareware. Copyright laws apply to both shareware and ordinary
for reuse by readers. Sybex grants readers limited permission to
commercial software, and the copyright Owner(s) retains all rights. If
reuse the code found in this publication, and available for down-
you try a shareware program and continue using it, you are expected
load from our website so long as the author(s) are attributed in
to register it. Individual programs differ on details of trial periods,
any application containing the reusable code and the code itself is
registration, and payment. Please observe the requirements stated in
never distributed, posted online by electronic transmission, sold,
appropriate files.
or commercially exploited as a stand-alone product.
Copy Protection
Software Support
The Software in whole or in part may or may not be copy-protected
Components of the supplemental Software and any offers associ-
or encrypted. However, in all cases, reselling or redistributing these
ated with them may be supported by the specific Owner(s) of that
files without authorization is expressly forbidden except as specifi-
material, but they are not supported by SYBEX. Information
cally provided for by the Owner(s) therein.
regarding any available support may be obtained from the Owner(s)
4176FM 11/6/02 3:14 PM Page iv

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 school
kids how to program. Thanks, Sister. “Trust in
the Lord with all your heart and lean not on your
own 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 v

Acknowledgments

irst, all honor, glory, and praise goes to God, who through His Son, all things are possible,
F 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 the
opportunity 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 into
perfect sentences, and to Dan Frumin, the Technical Editor, for going above and beyond
the 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 vi

Contents at a Glance

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


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

Chapter 15: Active Directory 535

Chapter 16: Remoting 563

Chapter 17: Security 593

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

Contents

Introduction xix

Part I Network Programming Basics 1

Chapter 1 The C# Language 3


Basics of .NET 4
Common Language Runtime (CLR) 4
MSIL Code 5
Installing a C# Development Environment 6
C# Development Options 7
Downloading the .NET Framework SDK 8
Installing the .NET Framework SDK 9
The C# Runtime Environment 10
Downloading and Installing the C# Runtime Package 11
Developing with the C# Runtime 11
C# Programming Basics 12
Creating C# Programs 12
Compiling and Running C# Programs 15
Using Multiple Source Files 16
Debugging C# Programs 17
Debugging MSIL Code 22
C# Features 23
C# Namespaces 24
Using Strings in C# Programs 28
C# Streams 33
C# Exception Programming 36
Summary 39
4176FM 11/6/02 3:14 PM Page x

x Contents

Chapter 2 IP Programming Basics 41


Watching Network Traffic 42
Installing the WinPcap Programs 43
The WinDump Program 44
The Analyzer Program 48
Analyzing Network Packets 51
The Ethernet Layer 51
The IP Layer 56
The TCP Layer 61
The UDP Layer 68
Programming with TCP and UDP 69
TCP Programming Features 70
UDP Programming Features 71
Finding IP Address Information 72
Using ipconfig 72
Using the Registry 74
Using WMI 80
Using DNS 83
Summary 84

Chapter 3 C# Network Programming Classes 87


A Primer on Socket Programming 88
Socket Programming in Windows 98
C# Socket Programming 103
IP Addresses in C# 103
Using C# Sockets 108
C# Socket Exceptions 119
C# Socket Helper Classes 120
TcpClient 120
TcpListener 122
UdpClient 123
Summary 124

Chapter 4 DNS and C# 125


The Domain Name System (DNS) 127
DNS Structure 127
Finding a Hostname in DNS 130
4176FM 11/6/02 3:14 PM Page xi

Contents xi

The DNS Database 131


A Sample DNS Database 136
Windows DNS Client Information 138
DNS Configuration 138
Using C# to Investigate the DNS Configuration 141
Resolving Hostnames with nslookup 144
DNS Classes in C# 153
Synchronous Methods 153
Asynchronous Methods 159
Summary 164

Part II Network Layer Programing 165

Chapter 5 Connection-Oriented Sockets 167


A Simple TCP Server 168
Creating the Server 168
Testing the Server 172
Watching the Server 172
A Simple TCP Client 173
Creating the Client 174
Testing the Client 176
When TCP Goes Bad 177
Problems with Data Buffers 177
Problems with TCP Messages 180
Solving the TCP Message Problem 184
Using C# Streams with TCP 198
The NetworkStream Class 198
The StreamReader and StreamWriter Classes 202
Summary 207

Chapter 6 Connectionless Sockets 209


A Simple UDP Application 210
The UDP Server 211
A UDP Client 215
Testing the Client and Server Programs 217
Using Connect() in a UDP Client Example 219
4176FM 11/6/02 3:14 PM Page xii

xii Contents

Distinguishing UDP Messages 220


When UDP Goes Bad 223
Preventing Lost Data 223
Preventing Lost Packets 228
A Complete UDP Application 242
Catching Multiple Exceptions by Monitoring Error Codes 242
The Complete Client Program 245
Summary 247

Chapter 7 Using The C# Sockets Helper Classes 249


The TcpClient Class 250
The TcpClient Class Constructors 250
The TcpClient Class Methods 251
Creating a Simple Client Program 252
Testing the Program 254
The TcpListener Class 255
The TcpListener Class Constructors 255
The TcpListener Class Methods 256
A Simple Server Program 257
Incorporating the StreamReader and StreamWriter Classes 258
The UdpClient Class 259
The UdpClient Class Constructors 259
The UdpClient Class Methods 260
Using the UdpClient Class in Programs 260
A Simple UdpClient Server Program 262
A Simple UdpClient Client Program 263
Testing the Sample Programs 264
Moving Data across the Network 265
Moving Binary Data 265
Communicating with Other Host Types 272
Moving Complex Objects 280
Summary 288

Chapter 8 Asynchronous Sockets 291


Windows Event Programming 292
Using Events and Delegates 293
4176FM 11/6/02 3:14 PM Page xiii

Contents xiii

The AsyncCallback Class 297


Using Asynchronous Sockets 298
Establishing the Connection 298
Sending and Receiving Data 301
Sample Programs Using Asynchronous Sockets 304
The Client Program 305
The Server Program 312
Using Non-blocking Socket Methods 319
The Poll() Method 319
The Select() Method 324
Summary 331

Chapter 9 Using Threads 333


How Applications Run in Windows 334
Finding Process Information Using C# 335
Threads 343
Creating Threads in a Program 350
The Thread Class 350
Using the Thread Class 351
Using Threads in a Server 354
Creating a Threaded Server 354
Testing the Server 357
Watching the Threads 357
Using Threads for Sending and Receiving Data 358
The TcpChat Program 359
Testing the Chat Program and Watching the Threads 363
Thread Pools 364
The ThreadPool Class 365
A Sample ThreadPool Program 366
Testing the Program and Watching the Threads 367
Using Thread Pools in a Server 369
A ThreadPool Server 369
Testing the Program and Watching the Threads 371
Summary 373

You might also like