TCP/IP Networking in .NET

This section details the .NET namespaces and classes that provide functionality for working with the Transmission Control Protocol/Internet Protocol (TCP/IP) suite. TCP/IP is the foundational protocol suite for the Internet and most private networks, enabling reliable, connection-oriented communication.

System.Net.Sockets Namespace

This namespace provides low-level access to network services, including the implementation of the Socket class, which is the core abstraction for network communication.

Key Classes and Concepts:

Common Operations:

Creating a Socket:


using System.Net.Sockets;

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            

Connecting to a Server (Client):


IPAddress ipAddress = IPAddress.Parse("192.168.1.100");
int port = 8080;
IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

socket.Connect(remoteEP);
            

Listening for Connections (Server):


IPAddress ipAddress = IPAddress.Any; // Listen on all network interfaces
int port = 8080;
IPEndPoint localEP = new IPEndPoint(ipAddress, port);

socket.Bind(localEP);
socket.Listen(10); // Maximum number of pending connections

Socket handler = await socket.AcceptAsync(); // Accept incoming connection
            

Sending and Receiving Data:


byte[] bytes = new byte[1024];
string data = null;

int bytesRec = handler.Receive(bytes);
data = System.Text.Encoding.ASCII.GetString(bytes, 0, bytesRec);

// Send data back to client
byte[] msg = System.Text.Encoding.ASCII.GetBytes("Message received");
handler.Send(msg);

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

System.Net Namespace

While System.Net.Sockets provides the core TCP/IP implementation, the System.Net namespace offers higher-level abstractions and utility classes for network operations.

Key Classes and Concepts:

Advanced Topics

Beyond basic socket programming, .NET supports:

For more detailed information on specific classes and methods, please refer to the API documentation for the System.Net.Sockets and System.Net namespaces.