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
-
optionLevel:
A
enumeration value that specifies the socket option level. Common values include SocketOptionLevel.Socket,SocketOptionLevel.IP, andSocketOptionLevel.Tcp. -
optionName:
A
enumeration value that specifies the name of the socket option to set. Examples include SocketOptionName.KeepAlive,SocketOptionName.Linger, andSocketOptionName.DontFragment. -
optionValue:
The value of the socket option to set. This can be an integer (for options like
SocketOptionName.Broadcast) or an object (for options likeSocketOptionName.Linger, which expects aLingerOptionobject).
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:
SocketOptionName.KeepAlive: Enables or disables periodic keep-alive messages to detect dead connections.SocketOptionName.Linger: Configures linger behavior, which determines how pending data is handled when the socket is closed.SocketOptionName.NoDelay: Disables the Nagle algorithm for TCP sockets, which can improve latency for small, frequent data transmissions.SocketOptionName.DontFragment: Prevents the underlying IP layer from fragmenting IP datagrams (for IPv4).SocketOptionName.ReuseAddress: Allows a socket to be bound to an address that is already in use.
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:
ArgumentOutOfRangeException: IfoptionLevelis not a valid socket option level.SocketException: If an error occurs during socket operation, such as the socket being closed or unavailable.ArgumentException: IfoptionValueis invalid for the specified option.ObjectDisposedException: If theSocketobject has been disposed.NotSupportedException: If the specifiedoptionNameis not supported by the underlying operating system or protocol.
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