SocketException Class

Namespace: System.Net.Sockets
Assembly: System.Net.Sockets.dll

The SocketException class represents an error generated by a socket operation. It provides detailed information about the specific socket error that occurred, allowing developers to diagnose and handle network-related issues effectively.

Properties

ErrorCode

Gets the error code associated with the exception.

public int ErrorCode { get; }

SocketErrorCode

Gets the SocketError enumeration value that represents the specific socket error.

public SocketError SocketErrorCode { get; }

Common SocketException Errors

SocketException can be thrown for a wide variety of reasons. Here are some of the most common ones you might encounter:

SocketError.ConnectionRefused

This error typically occurs when a client attempts to connect to a server port, but no process is listening on that port, or a firewall is blocking the connection. The server actively rejected the connection attempt.

Scenario:

Trying to connect to a web server that is not running.

SocketError.HostNotFound

This indicates that the remote host name could not be resolved. The DNS server was unable to find an IP address for the specified hostname.

Scenario:

Typing an incorrect or non-existent domain name into a browser.

SocketError.TimedOut

The connection attempt took too long to establish, and the operation was aborted. This can happen due to network congestion, a slow server, or a firewall silently dropping packets.

Scenario:

A client trying to reach a server that is online but unresponsive or overloaded.

SocketError.NetworkUnreachable

The client's operating system could not find a route to the destination network. This often points to issues with the local network configuration or routing tables.

Scenario:

Trying to access an external resource when your computer's network adapter is disabled or misconfigured.

SocketError.ConnectionReset

The connection was abruptly closed by the remote host. This can happen if the server crashes, restarts, or closes the connection without a proper handshake.

Scenario:

A client is communicating with a server, and the server process is terminated unexpectedly.

Handling SocketExceptions

It is crucial to wrap socket operations in try-catch blocks to gracefully handle potential SocketExceptions. This allows your application to respond appropriately, such as informing the user, retrying the operation, or logging the error.

Example Usage (C#):


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

public class SocketClient
{
    public static void Main(string[] args)
    {
        Socket socket = null;
        try
        {
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse("192.168.1.100"), 8080);
            socket.Connect(remoteEndPoint);
            Console.WriteLine("Successfully connected.");
            // ... perform send/receive operations
        }
        catch (SocketException socketEx)
        {
            Console.WriteLine($"Socket Error Code: {socketEx.ErrorCode}");
            Console.WriteLine($"Socket Error: {socketEx.SocketErrorCode}");
            Console.WriteLine($"Message: {socketEx.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"General Error: {ex.Message}");
        }
        finally
        {
            if (socket != null && socket.Connected)
            {
                socket.Shutdown(SocketShutdown.Both);
                socket.Close();
            }
        }
    }
}
            

See Also

SocketException .NET Framework Network Programming Error Handling System.Net.Sockets TCP/IP