A question came me today about if it was possible to do in managed code what the native winsock WSAIoctl(SOL_KEEPALIVE_VALS) function does.  The answer is yes.

First, if you simply want to turn on keep-alives you can use this simple method in the Socket class:

Socket s;
// first you need to Connect, then...
s.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

Of course to turn it back off just change the last param to false.

However if you want to specify the timing parameters for keep-alive you can use the Socket.IOControl method.  Here's a function that essentially duplicates what you can do with the native WSAIoctl function:

static void SetKeepAlive(Socket s, bool on, uint time, uint interval) {
/* the native structure
struct tcp_keepalive {
ULONG onoff;
ULONG keepalivetime;
ULONG keepaliveinterval;
};
*/

// marshal the equivalent of the native structure into a byte array
uint dummy = 0;
byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3];
BitConverter.GetBytes((uint)(on ? 1 : 0)).CopyTo(inOptionValues, 0);
BitConverter.GetBytes((uint)time).CopyTo(inOptionValues, Marshal.SizeOf(dummy));
BitConverter.GetBytes((uint)interval).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);
// of course there are other ways to marshal up this byte array, this is just one way

// call WSAIoctl via IOControl
int ignore = s.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);

}