Skip to content

Instantly share code, notes, and snippets.

@wberdowski
Created June 15, 2023 18:37
Show Gist options
  • Save wberdowski/975ac7bedf5a67a315b1dd65bb25569b to your computer and use it in GitHub Desktop.
Save wberdowski/975ac7bedf5a67a315b1dd65bb25569b to your computer and use it in GitHub Desktop.
C# TCP Socket Keep Alive Extensions
using System.Net.Sockets;
using System.Runtime.InteropServices;
namespace SocketKeepAlive
{
public static class SocketKeepAlive
{
public static void SetKeepAlive(this Socket socket, bool enabled, int keepalivetime, int interval)
{
int size = Marshal.SizeOf((uint)0);
byte[] keepAlive = new byte[size * 3];
Buffer.BlockCopy(BitConverter.GetBytes((uint)(enabled ? 1 : 0)), 0, keepAlive, 0, size);
Buffer.BlockCopy(BitConverter.GetBytes((uint)keepalivetime), 0, keepAlive, size, size);
Buffer.BlockCopy(BitConverter.GetBytes((uint)interval), 0, keepAlive, size * 2, size);
socket.IOControl(IOControlCode.KeepAliveValues, keepAlive, null);
}
public static void EnableKeepAlive(this Socket socket, byte retryCount, int keepAliveTimeInSeconds, int keepAliveIntervalInSeconds)
{
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, (int)retryCount);
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, keepAliveTimeInSeconds);
socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, keepAliveIntervalInSeconds);
}
public static void DisableKeepAlive(this Socket socket)
{
socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, false);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment