Skip to content

Instantly share code, notes, and snippets.

@shi-yan
Created September 17, 2014 23:36
Show Gist options
  • Save shi-yan/611cc0221eeff1644797 to your computer and use it in GitHub Desktop.
Save shi-yan/611cc0221eeff1644797 to your computer and use it in GitHub Desktop.
Correct way to set tcp socket keepalive on Win, Mac and Linux. Verified with Wireshark.
void setTcpKeepalive(SOCKET &sockfd)
{
const uint32_t keepaliveIntervalSec = 10;
#ifdef _WIN32
tcp_keepalive keepaliveParams;
DWORD ret = 0;
keepaliveParams.onoff = 1;
keepaliveParams.keepaliveinterval = keepaliveParams.keepalivetime = keepaliveIntervalSec * 1000;
WSAIoctl(sockfd, SIO_KEEPALIVE_VALS, &keepaliveParams, sizeof(keepaliveParams), NULL, 0, &ret, NULL, NULL);
#elif __APPLE__
int on = 1, secs = keepaliveIntervalSec;
setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof(on));
setsockopt(sockfd, IPPROTO_TCP, TCP_KEEPALIVE, &secs, sizeof(secs));
#elif __linux
int32_t optval;
socklen_t optlen = sizeof(optval);
optval = 1;
setsockopt(sockfd, SOL_SOCKET, SO_KEEPALIVE, &optval, optlen);
const uint32_t keepaliveProbeCount = 20;
optval = keepaliveIntervalSec;
setsockopt(sockfd, SOL_TCP, TCP_KEEPIDLE, &optval, optlen);
setsockopt(sockfd, SOL_TCP, TCP_KEEPINTVL, &optval, optlen);
optval = keepaliveProbeCount;
setsockopt(sockfd, SOL_TCP, TCP_KEEPCNT, &optval, optlen);
#endif
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment