How to work with Sockets in C#

Take advantage of sockets in C# to implement inter-process communication for the purpose of sharing data over a network

Network Programming

Network Programming

Inter-process communication is the ability to exchange data between two or more connected processes and can be achieved using sockets. After a connection between the server and client, i.e., the server process and the client process is established, they can communicate for the purpose of exchanging data using sockets.

A socket is the end point of a bi-directional communication between two processes running over a network. You can leverage the System.Net and System.Net.Sockets namespaces to work with sockets in C#. While the former is used for high level operations using sockets, the latter is used for any low level operations when working with sockets.

When working with sockets you can use either the TCP/IP (Transmission Control Protocol/Internet protocol) or UDP/IP (User Datagram Protocol/Internet protocol) communication mechanisms. In order to exchange data between two or more processes over a network, you can take advantage of the TCP and UDP transport protocols. While the TCP (Transmission Control Protocol) is a secure and reliable connection oriented protocol, the UDP (User Datagram Protocol) is a relatively less secure or reliable, fast, and connectionless protocol.

The following code listing illustrates how you can take advantage of the System.Net.Dns class to display the IP address of your system.

public static void Main(string[] args)

        {

            string hostName = Dns.GetHostName();

            try

            {

                IPAddress[] ipAddress = Dns.Resolve(hostName).AddressList;

                foreach (IPAddress address in ipAddress)

                    Console.WriteLine("{0}/{1}", hostName, address);

            }

            catch (Exception ex)

            {

                Console.WriteLine("Error occurred: "+ex.Message);

            }

            Console.Read();

        }

Refer to the code listing above. While the Dns.GetHostName() method returns the name of the system, the Dns.Resolve() method is used to retrieve an array of type IPHostEntry.

Retrieving network information

The System.Net.NetworkInformation namespace can be used to retrieve network metadata (i.e., network changes, network events, properties, etc.) in C#. As an example, if you would like to check if a network connection is available, you can use the GetIsNetworkAvailable() method as shown below.

System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable();

Here's how you can call this method in your code.

Boolean networkAvailable = NetworkInterface.GetIsNetworkAvailable();

If you would like to monitor the changes in the IP address you can use the following events of the NetworkChange class.

System.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged

System.Net.NetworkInformation.NetworkChange.NetworkAddressChanged

To retrieve the information on the network interfaces you can use the GetAllNetworkInterfaces() method of the NetworkInterface class.

NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

After you have retrieved the list of all the network interfaces, you can use the following piece of code to display the information of each of the network interface in the console.

foreach (NetworkInterface networkInterface in networkInterfaces)

            {

                Console.WriteLine("Network ID :  " + networkInterface.Id);

                Console.WriteLine("Network Name :  " + networkInterface.Name);

                Console.WriteLine("Network Description\n:  " + networkInterface.Description);               

            }

Here's the complete code listing for your reference.

static void Main(string[] args)

        {

            NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();

            foreach (NetworkInterface networkInterface in networkInterfaces)

            {

                Console.WriteLine("Network ID  :  " + networkInterface.Id);

                Console.WriteLine("Network Name  :  " + networkInterface.Name);

                Console.WriteLine("Network Description  \n:  " + networkInterface.Description);               

            }

            Console.Read();

        }

Client-Server programming

When working with network programming using TCP, you would typically need to create a server process that should start at a particular port and also a client process that can start on any port and send a connection request to the server. The server process after it is started, listens for incoming connection requests at the port on which it has been started. The following code snippet illustrates how you can take advantage of the System.Net.Sockets.TcpListener class and use it in conjunction with the socket class.

TcpListener listener = new TcpListener(1234);

listener.Start();

Socket socket = listener.AcceptSocket();

Stream networkStream = new NetworkStream(socket);

The following code snippet illustrates how your socket client can connect to the server using TCP protocol.

String ipAddress = "specify the ip address here";

System.Net.IPAddress ipAddress = System.Net.IPAddress.Parse(ipAddress);

System.Net.IPEndPoint remoteEndPoint = new IPEndPoint (ipAddress,9000);

socketClient.Connect (remoteEndPoint);

To send data to the server from the client, you can use the following code snippet.

try

{

  String text = "Hello World!";

  byte[] data = System.Text.Encoding.ASCII.GetBytes(text);

  socketClient.Send(data);

}

catch (SocketException se)

{

  //Write your exception handling code here

}

The Receive() method of the socket class can be used to receive data. Here's how you can use it to retrieve data from a socket. Note that both the Send and Receive methods are blocking, i.e., they would block the currently executing thread till data has been sent or received.

byte[] data = new byte[1024];

int i = socketClient.Receive (data);

Note that you should incorporate the System.Net and System.Net.Sockets namespaces in your program to work with sockets.

using System.Net;

using System.Net.Sockets;

This article is published as part of the IDG Contributor Network. Want to Join?

From CIO: 8 Free Online Courses to Grow Your Tech Skills
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.