Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to configure TCP_KEEPALIVE under MAC OS X

Tags:

c++

c

macos

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.

like image 559
House.Lee Avatar asked Apr 07 '13 07:04

House.Lee


1 Answers

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.

like image 60
Mischa Avatar answered Sep 21 '22 20:09

Mischa