.NET Networking

This section provides comprehensive documentation on how to perform network operations using the .NET Framework and .NET Core.

Overview of .NET Networking

The .NET platform offers a rich set of classes for network programming, abstracting away much of the complexity of underlying network protocols. These classes are primarily found in the System.Net namespace and its sub-namespaces.

Key Features:

Common Networking Tasks

Making HTTP Requests

The HttpClient class is the modern, recommended way to send HTTP requests. It supports asynchronous operations and offers flexibility in configuring requests.

using System.Net.Http;
using System.Threading.Tasks;

public class HttpExample
{
    public static async Task GetRequestAsync()
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                HttpResponseMessage response = await client.GetAsync("https://example.com/api/data");
                response.EnsureSuccessStatusCode(); // Throws if HTTP status code is not 2xx
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine(responseBody);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Request error: {e.Message}");
            }
        }
    }
}

Working with TCP Sockets

For lower-level network communication, System.Net.Sockets provides classes like Socket, TcpClient, and TcpListener.

System.Net.Sockets.TcpClient

Represents a Transmission Control Protocol (TCP) client, which provides a stream for sending and receiving data over a network.

System.Net.Sockets.TcpListener

Listens for incoming connection requests.

using System.Net;
using System.Net.Sockets;
using System.Text;

public class TcpServerExample
{
    public static void StartServer(int port)
    {
        TcpListener server = null;
        try
        {
            server = new TcpListener(IPAddress.Any, port);
            server.Start();

            Console.WriteLine("Server started. Waiting for connections...");

            while (true)
            {
                TcpClient client = server.AcceptTcpClient();
                Console.WriteLine("Client connected!");

                // Handle client connection in a separate thread or task
                // For simplicity, we'll just handle one here
                NetworkStream stream = client.GetStream();
                byte[] buffer = new byte[1024];
                int bytesRead = stream.Read(buffer, 0, buffer.Length);
                string data = Encoding.ASCII.GetString(buffer, 0, bytesRead);
                Console.WriteLine($"Received: {data}");

                byte[] msg = Encoding.ASCII.GetBytes("Hello from server!");
                stream.Write(msg, 0, msg.Length);
                Console.WriteLine("Sent: Hello from server!");

                client.Close();
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine($"SocketException: {e}");
        }
        finally
        {
            server?.Stop();
        }
    }
}

DNS Resolution

Use the Dns class to resolve host names to IP addresses and vice versa.

using System.Net;

public class DnsExample
{
    public static void ResolveHostname(string hostname)
    {
        try
        {
            IPAddress[] addresses = Dns.GetHostAddresses(hostname);
            Console.WriteLine($"IP addresses for {hostname}:");
            foreach (var address in addresses)
            {
                Console.WriteLine($"- {address}");
            }
        }
        catch (SocketException e)
        {
            Console.WriteLine($"Error resolving {hostname}: {e.Message}");
        }
    }
}

Related Topics