SocketOptionLevel Enum

Namespace: System.Net.Sockets

Specifies the option level to be used with the Socket.SetOptions and Socket.GetOptions methods.

Members

Remarks

The SocketOptionLevel enumeration is used to specify the category of socket options that you want to set or retrieve. For example, to set the ReuseAddress option for a TCP socket, you would use SocketOptionLevel.Socket as the option level and SocketOptionName.ReuseAddress as the option name.

Example

The following code example demonstrates how to set the ReuseAddress option on a socket to allow it to bind to an address that is already in use.


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

public class SocketOptionExample
{
    public static void Main(string[] args)
    {
        Socket socket = null;
        try
        {
            // Create a TCP socket.
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

            // Set the ReuseAddress option to true.
            // This allows the socket to bind to an address that is already in use.
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);

            Console.WriteLine("Socket option 'ReuseAddress' set to true.");

            // Proceed with binding and connecting logic...
            // Example:
            // socket.Bind(new IPEndPoint(IPAddress.Any, 12345));
            // socket.Listen(10);
            // Console.WriteLine("Socket listening on port 12345.");

        }
        catch (SocketException socketEx)
        {
            Console.WriteLine($"SocketException: {socketEx.Message}");
        }
        catch (Exception ex)
        {
            Console.WriteLine($"An error occurred: {ex.Message}");
        }
        finally
        {
            if (socket != null && socket.Connected)
            {
                socket.Shutdown(SocketShutdown.Both);
            }
            socket?.Close();
        }
    }
}