.NET API Reference

SocketException Class

System.Net.Sockets

Represents an error that occurs during a socket operation.

Inheritance: Object > Exception > SystemException > SocketException

Constructors

Properties

Methods

SocketException()

Initializes a new instance of the SocketException class.

SocketException(Int32 errorCode)

Initializes a new instance of the SocketException class with the specified error code.

Parameters

SocketException(String message)

Initializes a new instance of the SocketException class with a specified error message.

Parameters

SocketException(String message, Exception innerException)

Initializes a new instance of the SocketException class with a specified error message and a reference to the inner exception that is the cause of this exception.

Parameters

Remarks

The SocketException class is used to report errors that occur during socket operations. The ErrorCode property provides specific information about the error that occurred. This property can be used to retrieve a system-defined error code for the socket error.

Common socket error codes include:

Example


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

public class SocketExceptionExample
{
    public static void Main(string[] args)
    {
        try
        {
            // Attempt to connect to a non-existent server to trigger an exception
            using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                IPAddress ipAddress = IPAddress.Parse("192.168.1.254"); // Example of a potentially unreachable IP
                int port = 12345; // Example of a closed port
                IPEndPoint remoteEP = new IPEndPoint(ipAddress, port);

                socket.Connect(remoteEP);
            }
        }
        catch (SocketException se)
        {
            Console.WriteLine($"SocketException caught: {se.Message}");
            Console.WriteLine($"Error Code: {se.ErrorCode}");
            // You can look up the error code in Windows Sockets API documentation
            // or use a helper method to translate it to a string.
        }
        catch (Exception e)
        {
            Console.WriteLine($"An unexpected error occurred: {e.Message}");
        }
    }
}