Socket.SetSocketOption Method (SocketOptionLevel, SocketOptionName, Boolean)


Sets the specified Socket option to the specified Boolean value.

Namespace:   System.Net.Sockets
Assembly:  System (in System.dll)

public void SetSocketOption(
	SocketOptionLevel optionLevel,
	SocketOptionName optionName,
	bool optionValue


Type: System.Net.Sockets.SocketOptionLevel

One of the SocketOptionLevel values.

Type: System.Net.Sockets.SocketOptionName

One of the SocketOptionName values.

Type: System.Boolean

The value of the option, represented as a Boolean.

Exception Condition

The Socket object has been closed.


An error occurred when attempting to access the socket. See the Remarks section for more information.

Socket options determine the behavior of the current Socket. Set optionValue to true to enable the option, or to false to disable the option.

Socket options are grouped by level of protocol support.

Listed below are the various Socket options that can be set using this overload. These options are grouped by the appropriate SocketOptionLevel value. If you intend to set any of these options, be sure to use the appropriate SocketOptionLevel value for the optionLevel parameter. The option you choose to set must be specified in the optionName parameter. If you want to get the current value of any of the options listed, use the GetSocketOption method.

SocketOptionLevel.Socket options that can be set using this overload.

SocketOptionLevel.IP options that can be set using this overload.

SocketOptionLevel.Tcp options that can be set using this overload.

SocketOptionLevel.Udp options that can be set using this overload.

For more information on these options, refer to the SocketOptionName enumeration.


If you receive a SocketException exception, use the SocketException.ErrorCode property to obtain the specific error code. After you have obtained this code, refer to the Windows Sockets version 2 API error code documentation in the MSDN library for a detailed description of the error.

The following code example opens a socket and enables the DontLinger and the OutOfBandInline socket options.

// Establish the local endpoint for the socket.
IPHostEntry ipHost = Dns.GetHostEntry(Dns.GetHostName());
IPAddress  ipAddr = ipHost.AddressList[0];
IPEndPoint ipEndPoint = new IPEndPoint(ipAddr, 11000);

// Create a TCP socket.
Socket client = new Socket(AddressFamily.InterNetwork,
    SocketType.Stream, ProtocolType.Tcp);

// Connect the socket to the remote endpoint.

// Set option that allows socket to close gracefully without lingering.
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, true);

// Set option that allows socket to receive out-of-band information in the data stream.
client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.OutOfBandInline, true);

.NET Framework
Available since 2.0
Return to top