首先,您需要确保在系统上启用了TCP keepalive。您可以像这样检查默认设置:
# sysctl net.ipv4.tcp_keepalive_time net.ipv4.tcp_keepalive_probes net.ipv4.tcp_keepalive_intvl
net.ipv4.tcp_keepalive_time = 7200
net.ipv4.tcp_keepalive_probes = 9
net.ipv4.tcp_keepalive_intvl = 75
然后确保您在代码中正确设置了它。它看起来应该像这样:
int optval = 1;
if (setsockopt(s, SOL_SOCKET, SO_KEEPALIVE, &optval, sizeof(optval)) < 0) {
perror("setsockopt()");
close(s);
exit(EXIT_FAILURE);
}
在我的系统上,当我使用上述代码在两侧设置SO_KEEPALIVE时,我看到:
tcp 0 0 127.0.0.1:48591 127.0.0.1:5555 ESTABLISHED keepalive (6958.37/0/0)
tcp 0 0 127.0.0.1:5555 127.0.0.1:48591 ESTABLISHED keepalive (6958.37/0/0)
然后,我用Wireshark验证了NOP
保持连接已发送。
可以在TCP Keepalive HOWTO中找到更多详细信息。