Jeff here again from the Windows SDK Team.
Recently, I had a case where the customer required use of the TCP Linger option to reset a connection when it was closed.
I was able to get it to work in native Winsock with no problem, but getting the reset to be sent in .NET was rather elusive. I spend
much more of my time working in native rather than managed code, so maybe this is more obvious to others than it was to myself.
Here is the Linger option I wanted to set:
LingerOption lingerOption = new LingerOption(true, 0);
// Set the Linger Option on the TCPClient.Client
client.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, lingerOption);
The sample from MSDN for TcpListener creates a server that accepts client connections. The sample closes the client with this code:
// Close connection
However, this won’t invoke the Linger settings and reset the connection. To do that we need to close the client connection in the client this
// Close connection AND RST the connection
Closing the connection this way sends a RST to the client and lets them know that the
connection has been closed and no further data will be accepted. Otherwise, the
client wouldn’t know it was closed until they tried to send data to it again.
Follow us on Twitter, www.twitter.com/WindowsSDK.