Reputation: 251
Currently I've encountered this problem: how to detect unpredictable connection broken.
I utilized SO_KEEPALIVE,TCP_KEEPIDLE,TCP_KEEPINTVL and TCP_KEEPCNT to solve it under linux, which seems working fine now.
However, It really took me a long time to find out how to work it out under MAC OS X. Somebody suggested me to turn to netinet/tcp_var.h, but still none of the aforementioned MACRO was found.
So, my question is,
How to implementation TCP KEEPALIVE under MAC OS X?
P.S.: my MAC OS X version is 10.8.3,and my gcc/g++ version is 4.2.1
Any reply would be appreciated.
Upvotes: 8
Views: 19301
Reputation: 2288
Actually, Darwin (BSD) is simpler than Linux. Set the TCP_KEEPALIVE (secs) option, as well as the SO_KEEPALIVE (bool) option:
int on = 1, secs = 10;
setsockopt(skt, SOL_SOCKET, SO_KEEPALIVE, &on, sizeof on);
setsockopt(skt, IPPROTO_TCP, TCP_KEEPALIVE, &secs, sizeof secs);
To see what the default interval is (if you just did the SO_KEEPALIVE), use:
sysctl -A | grep net.inet.tcp.*keep
You'll probably see:
net.inet.tcp.keepidle: 7200000
net.inet.tcp.keepintvl: 75000
net.inet.tcp.keepinit: 75000
net.inet.tcp.always_keepalive: 0
i.e. keepalive is only on for sockets with SO_KEEPALIVE set, and the idle timeout is 72000.000 msecs (2 hours). HTH.
Upvotes: 15
Reputation: 46051
I think you should use setsockopt()
, see it's man page
It looks like the TCP_KEEPIDLE
, TCP_KEEPINTVL
and TCP_KEEPCNT
are Linux specific and you won't find their equivalent counter parts on OSX.
To set the SO_KEEPALIVE
do this
int optval = 1;
setsockopt(sock, SOL_SOCKET, &optval, sizeof(optval));
Another trick I used long time ago was to try to send 0 (zero) number of bytes, this would check that a socket is still alive. Either as a repetitive watch dog or just before trying to send a message.
Upvotes: 0