12

I am using winsock and TCP. I have set the KeepAlive option as follows

int aliveToggle = 1;
setsockopt(mySocket,SOL_SOCKET,SO_KEEPALIVE,(char*)&aliveToggle, sizeof(aliveToggle));

But how to specify the Keep aLive time and interval?

I am using VC++ running on windows 7.

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
xaria
  • 842
  • 5
  • 24
  • 47
  • Under Linux there are TCP_KEEPIDLE, TCP_KEEPCNT, and TCP_KEEPINTVL options that let you control the keepalive behavior... but AFAIK under Windows you're pretty much out of luck. Hopefully I'm wrong and someone will post a method here, if there is one that I missed I'd like to know also :) – Jeremy Friesner Nov 18 '11 at 01:54

2 Answers2

20

From c/c++ you should be able to use SIO_KEEPALIVE_VALS to control the timeouts. You can't use setsockopt, but you should be able to use WSAIoctl. See https://web.archive.org/web/20130828175019/http://msdn.microsoft.com/en-us/library/windows/desktop/dd877220(v=vs.85).aspx

Here's an example https://web.archive.org/web/20130827074722/http://read.pudn.com/downloads79/ebook/301417/Chapter09/SIO_KEEPALIVE_VALS/alive.c__.htm

Joseph Quinsey
  • 9,553
  • 10
  • 54
  • 77
Eugene Marcotte
  • 751
  • 8
  • 21
  • 1
    Sorry bout that, the answer is from 7 years ago so I guess microsoft has moved things around. The first is https://learn.microsoft.com/en-us/windows/win32/winsock/sio-keepalive-vals – Eugene Marcotte May 14 '21 at 13:38
7

Two per-interface registry settings under the key \HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Tcpip\Parameters control the behavior of TCP/IP keep-alives:

The KeepAliveTime value specifies how long the TCP connection sits idle, with no traffic, before TCP sends a keep-alive packet. The default is 7,200,000 milliseconds (ms) or 2 hours.

The KeepAliveInterval value indicates how many milliseconds to wait for a response after sending a keep-alive before repeating the keep-alive. If no response is received, the TCP/IP stack continues sending keep-alives at this interval until a response is received or until the stack reaches the packet retry limit specified in the TCPMaxDataRetransmissions registry key. KeepAliveInterval defaults to 1 second (1000 .

TCP keep-alives are disabled by default, but Windows Sockets applications can use the setsockopt function to enable them on a per-connection basis.

Note  If the developer elects to use TCP keep-alive messages on a particular connection, the timing of those messages is specified by the registry values described preceding. It is not possible to use different timing on different keep-alive requests.

ComfortablyNumb
  • 3,391
  • 2
  • 14
  • 15