.NET Documentation

Networking in .NET

The .NET platform provides a comprehensive set of classes for developing network-aware applications. These classes are found in the System.Net namespace and its sub-namespaces. They enable you to perform a wide range of networking tasks, from simple HTTP requests to complex socket programming.

Key Networking Components

The .NET networking stack is built around several key abstractions:

Common Networking Scenarios

1. Making HTTP Requests

The most common networking task is making HTTP requests to retrieve data from web servers. .NET offers several classes for this, with HttpClient being the modern and recommended approach.

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

public class HttpExample
{
    public static async Task Main(string[] args)
    {
        using (HttpClient client = new HttpClient())
        {
            try
            {
                string url = "https://www.example.com";
                HttpResponseMessage response = await client.GetAsync(url);
                response.EnsureSuccessStatusCode(); // Throw if HTTP status is not success
                string responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"Successfully fetched content from {url}:");
                Console.WriteLine(responseBody.Substring(0, Math.Min(responseBody.Length, 500)) + "..."); // Display first 500 chars
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine($"Request error: {e.Message}");
            }
        }
    }
}

2. Socket Programming (TCP/UDP)

For lower-level network communication, you can use the classes in the System.Net.Sockets namespace. This allows for direct communication between two network endpoints.

TCP Sockets

TCP (Transmission Control Protocol) provides a reliable, connection-oriented stream of data.

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

// Example for a simple TCP listener (server-side concept)
public class TcpListenerExample
{
    public static void StartListening()
    {
        TcpListener server = null;
        try
        {
            int port = 13000;
            IPAddress localAddr = IPAddress.Parse("127.0.0.1");
            server = new TcpListener(localAddr, port);
            server.Start();

            Console.WriteLine($"TCP Listener started on {localAddr}:{port}");

            // Accept a client connection
            TcpClient client = server.AcceptTcpClient();
            Console.WriteLine("Client connected!");

            // Get stream for reading/writing
            NetworkStream stream = client.GetStream();
            // ... handle data exchange ...

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

UDP (User Datagram Protocol) is a connectionless protocol that offers faster, but less reliable, data transmission.

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

// Example for sending a UDP datagram
public class UdpSenderExample
{
    public static void SendData()
    {
        using (UdpClient udpClient = new UdpClient())
        {
            IPEndPoint targetEP = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000); // Target port 11000
            byte[] data = Encoding.ASCII.GetBytes("Hello UDP!");
            udpClient.Send(data, data.Length, targetEP);
            Console.WriteLine("UDP datagram sent.");
        }
    }
}

3. DNS Resolution

Resolving host names to IP addresses is a fundamental networking operation. The System.Net.Dns class handles this.

using System;
using System.Net;

public class DnsExample
{
    public static void ResolveHost(string hostName)
    {
        try
        {
            IPHostEntry hostEntry = Dns.GetHostEntry(hostName);
            Console.WriteLine($"Host: {hostEntry.HostName}");
            Console.WriteLine("IP Addresses:");
            foreach (IPAddress ip in hostEntry.AddressList)
            {
                Console.WriteLine($"- {ip}");
            }
        }
        catch (Exception e)
        {
            Console.WriteLine($"Error resolving {hostName}: {e.Message}");
        }
    }
}

Further Reading

"The internet is a testament to humanity's ability to connect and share information on a global scale."