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:
Socket
: Represents a network endpoint and provides methods for sending and receiving data.IPAddress
: Represents an IP address.EndPoint
: An abstract base class representing a network endpoint.IPEndPoint
: Represents an endpoint of an IP address and port number.SocketException
: Handles errors that occur during socket operations.
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:
IPAddress
: As mentioned above, also resides here.Dns
: Provides DNS resolution capabilities.NetworkInformation
: Classes for querying network interface information.
Advanced Topics
Beyond basic socket programming, .NET supports:
- Asynchronous Operations: Using Begin/End methods or the Task Parallel Library (TPL) for non-blocking network I/O, crucial for scalable applications.
- Socket Options: Configuring various socket parameters like buffer sizes, keep-alives, and timeouts.
- Protocol Specifics: Understanding TCP's reliability, ordering, and flow control mechanisms.
- IPv6 Support: Utilizing
AddressFamily.InterNetworkV6
for IPv6 communication.
For more detailed information on specific classes and methods, please refer to the API documentation for the System.Net.Sockets
and System.Net
namespaces.