Friday 22 June 2012

TCP Keep Alive

How to know if remote TCP device is down?

By default, TCP blocking socket will block when remote TCP device is down. We can use TCP KEEPALIVE to check:

setsockopt(SOL_SOCKET, SO_KEEPALIVE,...);

and set the TCP keep alive settings:

sysctl -w net.ipv4.tcp_keepalive_intvl = 10
sysctl -w net.ipv4.tcp_keepalive_time = 30
sysctl -w net.ipv4.tcp_keepalive_probes = 2

Then, the socket recv() function will return -1 when remote device is down.