Login(Email) Password Forget Password? Account Settings
Home ASP.net System Info C# Books Java Script Visual C++(MFC) C/C++ Win API Java Contact Us

Network Programming in C#

INDEX

Part 1. IP Programming Basics

1.TCP : An Overview

a)TCP Application Ports

b)Establishing Session

     2.UDP : An Overview

         a)UDP ports

Part 2.C# Network Programming Basics

     1.What is Socket Programming

a) Sockets in general

      2.C# Socket Programming 

a)IP addresses in C#

i )IP address

ii) IPEndPoint

         b)Using C# sockets

              i )Socket Construction

              ii)Socket Options

              iii)Connection Oriented Sockets

                   a)Client Sockets

                   b)Server Sockets

              iv)Connectionless Sockets

         

  Part 3. Network Layer Programming      

          1.Using TCP with Connection Oriented Sockets

              i ) A Simple TCP server

              ii)A Simple TCP client

              iii)Using C# stream with TCP

         2.Using UDP with Connectionless Sockets

              i ) A simple UDP server

             ii) A simple UDP client

         3.Using C# Helper Classes

              i ) TCP Client Class

              ii)TCP Listener Class

              iii)UDP Client Class

   Part 4.Application Layer Programming

          1.Programming with ICMP

              i )ICMP in general

              ii)Raw Sockets

              iii)An ICMP class

              iv)A simple Ping Programe     

          2.Programming with SMTP

              i )SMTP & Email in general

              ii)The SmtpClass

              iii)Using Expanded Mail Message Formats

              iv)POP3 protocol in general

              v)A POP3 client

          3.Programming with HTTP

              i )The WebClient Class

              ii)Downloading Web Data methods

              iii)Viewing HTTP headers methods

              iv)Uploading Web Data  methods

              v)Credentials property

Part 1. IP Programming Basics

1.                 TCP: An Overview

  • Transmission Control Protocol (TCP) adds connection information to the data packet.
  • It creates an end-to-end connection  providing a consistent path for data to travel.

·        To communicate with an application on a remote device, you must know :

                                       i.      The remote device’s IP address

                                      ii.      The TCP port assigned to the remote application

                       

                                       Figure: Sample TCP connection

IP EndPoint:

The combination of an IP address and a port number defines an IP endpoint.

Session:

  • A TCP session is defined as the combination of a local IP endpoint and a remote IP endpoint.
  • Only one session can have both these properties the same.

NOTE:

  • Ports that are numbered from 0 to 1023 are called well-known ports because they are assigned to

          specific, common applications.

  • Ports numbered from 1024 to 65,535 are open for use by any application

 

Establishing a TCP Session:

The TCP header flags are used to control the TCP connection between the two devices.

Table: TCP Flags

Flag

Description

6 bits that are reserved

Reserved for future use—always zero

1-bit URG flag

Marks the packet as containing urgent data

1-bit ACK flag

Acknowledges receiving a packet

1-bit PUSH flag

Indicates data is to be pushed to the application immediately

1-bit RESET flag

Resets the TCP connection to the initial state

1-bit SYN flag

Indicates a TCP synchronization packet (start-of-session)

1-bit FIN flag

Indicates a TCP end-of-session

The TCP session has three phases:

·         Opening handshake:

1.   The originating host sends a SYN flag to indicate the start of a session.

2.      The receiving host sends both a SYN flag and an ACK flag in the same    packet to indicate it accepts

 the start of the session.

3.   The originating host sends an ACK flag to indicate the session is open and   ready for packets.

·         Session communication:

After the session is established, you will see the ACK flag set on packets,     indicating that the device is

 acknowledging the

receipt of a packet with a particular sequence number.

·         Closing handshake:

1.   The host initiating the close sends a FIN flag.

2.   The remote host sends both an ACK flag and a FIN flag in the same packet to indicate it accepts the end

of the session.

3.   The initiating host sends an ACK flag to officially close the session.  

Figure: The steps of the TCP handshake protocol

2.                 UDP: An Overview

Unlike TCP, UDP provides a connectionless path between network devices to transmit data, and thus does not need all of the

overhead of session establishment flags and connection states.

Each UDP “session” is nothing more than a single packet transmitted in one direction.

Like TCP, UDP tracks individual connections using port numbers and assigns port numbers from 0 to 1023 to reserved

application ports.

Ports 1024 to 65536 are available for you to use in your applications.

Part 2.C# Network Programming Basics

1. Sockets:

The special file descriptors used to reference network connections are called sockets. The socket defines the following:

·         A specific communication domain, such as a network connection or a Unix Interprocess Communication (IPC) pipe

·         A specific communication type, such as stream or datagram

·         A specific protocol, such as TCP or UDP

NOTE:

After the socket is created, it must be bound to either a specific network address and port on the local system,

or to a remote

 network address and port.

a)                            Connection-Oriented Sockets:

·  They use TCP protocol to establish a session (connection) between two IP address endpoints.

·  To create a connection-oriented socket, separate sequences of functions must be used for server programs

and for

  client programs

Figure: Connection-oriented socket programming functions

b)                              Connectionless Sockets:

·        They use the UDP protocol,

·        No connection information is required to be sent between network devices.

NOTE:

If a device is initially waiting for data from a remote device, the socket must be bound to a local address/port pair using the

  bind( ) function. Once this is done the device can send data out from the socket, or receive incoming data from the socket.

Figure: Connectionless socket programming functions

2. C# Socket Programming:

a)                    IP Addresses in C#:

           .NET defines two classes in the System.Net namespace to handle various types of IP address information:

·         IPAddress

·         IPEndPoint

       i. IPAddress :

An IPAddress object is used to represent a single IP address.

The default constructor for IPAddress is as follows:

public IPAddress(long address)
 
Methods:

Table: IPAddress Methods

Method

Description

Equals

Compares two IP addresses

GetHashCode

Returns a hash value for an IPAddress object

GetType

Returns the type of the IP address instance

HostToNetworkOrder

Converts an IP address from host byte order to network byte order

IsLoopBack

Indicates whether the IP address is considered the loopback address

NetworkToHostOrder

Converts an IP address from network byte order to host byte order

Parse

Converts a string to an IPAddress instance

ToString

Converts an IPAddress to a string representation of the dotted decimal format of the IP address

The Parse( ) method is most often used to create IPAddress instances:

IPAddress newaddress = IPAddress.Parse("192.168.1.1");

Properties:

Any              Used to represent any IP address available on the local system.

Broadcast    Used to represent the IP broadcast address for the local network.

Loopback     Used to represent the loopback address of the system.

None            Used to represent no network interface on the system.

ii.       IPEndPoint:

       IPEndPoint object is used to represent a specific IP address/port combination.

An IPEndPoint object is used when binding sockets to local addresses, or when connecting sockets to remote addresses.

Two constructors are used to create IPEndPoint instances:

·         IPEndPoint (long address, int port)

·         IPEndPoint (IPAddress address, int port)

Methods:

Table: IPEndPoint Methods

Method

Description

Create

Creates an EndPoint object from a SocketAddress object

Equals

Compares two IPEndPoint objects

GetHashCode

Returns a hash value for an IPEndPoint object

GetType

Returns type of the IPEndPoint instance

Serialize

Creates a SocketAddress instance of the IPEndPoint instance

ToString

Creates a string representation of the IPEndPoint instance

Properties:

Address               Gets or sets the IP address property

AddressFamily   Gets the IP address family

Port                      Gets or sets the TCP or UDP port number

b)             Sockets in C#:

The System.Net.Sockets namespace contains the classes that provide the actual .NET interface to the low-level Winsock APIs.

The core of the System.Net.Sockets namespace is the Socket class.

Socket Construction:

The Socket class constructor is as follows:

Socket(AddressFamily af, SocketType st, ProtocolType pt)

·          AddressFamily     to define the network type

·          SocketType           to define the type of data connection

·          ProtocolType        to define a specific network protocol

Table: IP Socket Definition Combinations

SocketType

Protocoltype

Description

Dgram

Udp

Connectionless communication

Stream

Tcp

Connection-oriented communication

Raw

Icmp

Internet Control Message Protocol

Raw

Raw

Plain IP packet communication

 
e.g. 
Socket newsock = Socket(AddressFamily.InterNetwork,
             SocketType.Stream,  ProtocolType.Tcp);

  i. Using Connection-Oriented Sockets:

Socket newsock = Socket(AddressFamily.InterNetwork,

                                         SocketType.Stream ,  ProtocolType.Tcp);

a.                 The Server Functions:

·                          Bind      (EndPoint address)

·                          Listen   (int backlog)  :

The backlog parameter defines the number of connections that   the system will        queue, waiting for your program

 to service.

 Any attempts by clients beyond that number of waiting connections will be refused.

·                          Accept( )

e.g.

IPHostEntry local = Dns.GetHostByName(Dns.GetHostName());
IPEndPoint iep = new IPEndPoint(local.AddressList[0], 8000);
Socket newserver = new Socket(AddressFamily.InterNetwork,
SocketType.Stream,ProtocolType.Tcp);
newserver.Bind(iep);
newserver.Listen(5);

Socket newclient = newserver.Accept ();

Table: The Receive() and Send() Methods

Method

Description

Receive(byte[] data)

Receives data and places it in the specified byte array

Receive(byte[] data, SocketFlags sf)

Sets socket attributes, receives data, and places it in the specified byte array

Receive(byte[] data, int size, SocketFlags sf)

Sets socket attributes, receives the specified size of data, and places it in the specified byte array

Receive(byte[] data, int offset, int size, SocketFlags sf)

Sets socket attributes, receives the size bytes of data, and stores it at offset offset in the data byte array

Send(byte[] data)

Sends the data specified in the byte array

Send(byte[] data, SocketFlags sf)

Sets socket attributes and sends the data specified in the bytes array

Send(byte[] data, int size, SocketFlags sf)

Sets socket attributes and sends the specified size of data in the specified byte array

Send(byte[] data, int offset, int size, SocketFlags sf)

Sets socket attributes and sends size bytes of data starting at offset offset in the data byte array

b.                 The Client Functions:

·        Connect(IPEndPoint)      Requires an IPEndPoint object for the remote    device to     which the  client needs to connect:

·                     Shutdown()                       To gracefully stop a session 
·                      Close( )            To actually close the session

The shutdown( ) method uses one parameter to determine how the socket will shutdown. Available values for Socket.Shutdown ( ) are described in Table.

Table: Socket.Shutdown Values

Value

Description

SocketShutdown.Both

Prevents both sending and receiving data on the socket

SocketShutdown.Receive

Prevents receiving data on the socket. An RST will be sent if additional data is received.

SocketShutdown.Send

Prevents sending data on the socket. A FIN will be sent after all remaining buffer data is sent.

Here is the typical way to gracefully close a connection:

sock.Shutdown(SocketShutdown.Both);
sock.Close();

       i. Using Connectionless Sockets:

·  The standard Receive( ) and Send() methods will not work.

·  Use the special ReceiveFrom ( ) and SendTo () methods.

·  For example, the simplest format of the methods would be as follows:

ReceiveFrom(byte[], ref EndPoint)
SendTo(byte[], ref EndPoint)

There is an extra parameter that is a reference to an EndPoint object.

 This parameter defines where the data is going (for SendTo ) or where it is coming from (for ReceiveFrom ).

  Part 3.Network Layer Programming

 

1.Using TCP with Connection Oriented Sockets

         i.            TCP Server:

 We have four tasks to perform before a server can transfer data with a client connection:

·         Create a socket

·         Bind the socket to a local IPEndPoint

·         Place the socket in listen mode