Socket.SetSocketOption Method

Socket.SetSocketOption Method

Sets the value of a specific socket option.

Syntax


<summary>
Sets the value of a specific socket option.
</summary>
<param name="optionLevel">The level of the option to set.</param>
<param name="optionName">The name of the option to set.</param>
<param name="optionValue">The value of the option to set.</param>
<exception cref="ArgumentOutOfRangeException"><paramref name="optionLevel" /> is not a valid socket option level.</exception>
<exception cref="SocketException">An existing socket was closed.</exception>
<exception cref="SocketException">An attempt to access a socket that is not available for access.</exception>
<exception cref="ArgumentException"><paramref name="optionValue" /> is not a valid value for the specified option.</exception>
<exception cref="ObjectDisposedException">The Socket has been closed.</exception>
<exception cref="NotSupportedException"><paramref name="optionName" /> is not supported.</exception>
public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, int optionValue);

<summary>
Sets the value of a specific socket option.
</summary>
<param name="optionLevel">The level of the option to set.</param>
<param name="optionName">The name of the option to set.</param>
<param name="optionValue">The value of the option to set.</param>
<exception cref="ArgumentOutOfRangeException"><paramref name="optionLevel" /> is not a valid socket option level.</exception>
<exception cref="SocketException">An existing socket was closed.</exception>
<exception cref="SocketException">An attempt to access a socket that is not available for access.</exception>
<exception cref="ArgumentException"><paramref name="optionValue" /> is not a valid value for the specified option.</exception>
<exception cref="ObjectDisposedException">The Socket has been closed.</exception>
<exception cref="NotSupportedException"><paramref name="optionName" /> is not supported.</exception>
public void SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, object optionValue);
                

Parameters

Remarks

The SetSocketOption method is used to configure various aspects of socket behavior. It allows you to control network protocols, optimize performance, and manage socket connections more effectively.

The available options depend on the protocol and the operating system. Some common socket options include:

When setting an option that requires a specific object type (e.g., SocketOptionName.Linger), ensure that you pass an instance of the correct type to the optionValue parameter. For integer options, the value is passed directly.

Exceptions

This method can throw several exceptions, including:

Example

Setting KeepAlive Option for a TCP Socket


using System;
using System.Net.Sockets;

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

        try
        {
            // Enable KeepAlive with a 30-second interval
            // Note: The actual keep-alive behavior is highly dependent on the OS.
            // The KEEPALIVE option often uses two values: enable (0 or 1) and the interval.
            // This example uses a simplified approach for demonstration.
            // For finer control, you might need to use IOCTLs or platform-specific methods.

            // First, set KeepAlive to true
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, 1);

            // For some systems, you might also need to set TCP_KEEPIDLE, TCP_KEEPINTVL, TCP_KEEPCNT
            // via SocketOptionLevel.Tcp. This often requires P/Invoke or platform-specific code.
            // For a basic example, we'll stick to the common SocketOptionName.KeepAlive.

            Console.WriteLine("KeepAlive option set to enabled for the socket.");

            // You would typically connect or bind the socket here
            // socket.Connect(...);
            // socket.Bind(...);

            // Example: Setting NoDelay to true to disable Nagle's algorithm
            socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1);
            Console.WriteLine("NoDelay option set to enabled (Nagle's algorithm disabled).");

            // Example: Setting Linger option
            // LingerOption lingerOpt = new LingerOption(true, 10); // Enable linger, timeout 10 seconds
            // socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOpt);
            // Console.WriteLine("Linger option set.");

        }
        catch (SocketException e)
        {
            Console.WriteLine($"SocketException: {e.Message}");
        }
        catch (ArgumentException e)
        {
            Console.WriteLine($"ArgumentException: {e.Message}");
        }
        finally
        {
            // Clean up the socket
            if (socket.Connected)
            {
                socket.Shutdown(SocketShutdown.Both);
            }
            socket.Close();
            Console.WriteLine("Socket closed.");
        }
    }
}
                    

Requirements

Namespace: System.Net.Sockets

Assembly: System.Net.Primitives.dll (in .NET Core and .NET 5+)

Assembly: System.dll (in .NET Framework)

Platform: Windows, macOS, Linux