Skip to content

TCP_KEEPALIVE, TCP_KEEPINTVL, and TCP_KEEPCNT Socket Options #19568

@caleblloyd

Description

@caleblloyd

I am trying to set per-socket keepalive TCP timeouts on Linux and MacOS. The following named socket options are not exposed, however:

  • SocketOptionName.TCP_KEEPALIVE
  • SocketOptionName.TCP_KEEPINTVL
  • SocketOptionName.TCP_KEEPCNT

When I try to add them using their POSIX codes, I get an exception:

  -------- System.Net.Sockets.SocketException : Operation not supported
       at System.Net.Sockets.Socket.SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, Int32 optionValue, Boolean silent)
       at System.Net.Sockets.Socket.SetSocketOption(SocketOptionLevel optionLevel, SocketOptionName optionName, Int32 optionValue)

Here is the code I'm using to try to add them with POSIX codes:

if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
	// Found these Socket Option Values at https://github.com/golang/go/search?utf8=%E2%9C%93&q=TCP_KEEPCNT
	// Linux/OSX takes time in seconds
	SocketOptionName tcpKeepIdle;
	SocketOptionName tcpKeepIntvl;
	SocketOptionName tcpKeepCnt;
	if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
	{
		tcpKeepIdle = (SocketOptionName)0x4; // TCP_KEEPIDLE
		tcpKeepIntvl = (SocketOptionName)0x5; // TCP_KEEPINTVL
		tcpKeepCnt = (SocketOptionName)0x6; // TCP_KEEPCNT
	}
	else
	{
		// TCP_KEEPALIVE option on OSX == TCP_KEEPIDLE on Linux
		// see https://www.winehq.org/pipermail/wine-devel/2015-July/108583.html
		tcpKeepIdle = (SocketOptionName)0x10; // TCP_KEEPALIVE
		tcpKeepIntvl = (SocketOptionName)0x101; // TCP_KEEPINTVL
		tcpKeepCnt = (SocketOptionName)0x102; // TCP_KEEPCNT
	}
	socket.SetSocketOption(SocketOptionLevel.Tcp, tcpKeepIdle, keepAliveTimeSeconds);
	socket.SetSocketOption(SocketOptionLevel.Tcp, tcpKeepIntvl, keepAliveIntervalSeconds);
	socket.SetSocketOption(SocketOptionLevel.Tcp, tcpKeepCnt, keepAliveCount);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    api-needs-workAPI needs work before it is approved, it is NOT ready for implementationarea-System.Nethelp wanted[up-for-grabs] Good issue for external contributorsos-linuxLinux OS (any supported distro)os-mac-os-xmacOS aka OSX

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions