TCP Keepalives are useful for scenarios where one end of the connection disappears without closing the connection. This can happen when a NAT or firewall resets, or forcibly closes the connection. The following code in Python enables sending a Keepalive message when there is no data activity over a socket for 60 seconds. If it does not get a response, it sends Keepalive messages 4 times at intervals of 15 seconds. After that, the connection is closed. The code has been tested with Python 2.7.2 and Ubuntu 12.04.
To test, create a TCP listener/server using netcat on a different PC (or nc on a Mac)
netcat -l 192.168.0.120 8001
Now, disable the network connection, enable a firewall, or power off the router, to see Keepalive in action. Wireshark highlights Keepalive messages when TCP sequence number analysis is enabled.
You’ll see the following messages when the connection times out
Traceback (most recent call last): File "socket_test.py", line 39, in do_work req = sock.recv(10) error: [Errno 110] Connection timed out Other Socket err, exit and try creating socket again
On Mac and Windows you can enable Keepalive, but cannot set TCP_KEEPIDLE and other parameters. You’ll get the following error message (Python 2.7.2 with macports) if you try to do so
Traceback (most recent call last): File "socket_test.py", line 65, in <module> do_work() File "socket_test.py", line 19, in do_work sock.setsockopt(socket.SOL_TCP, socket.TCP_KEEPIDLE, 60) AttributeError: 'module' object has no attribute 'TCP_KEEPIDLE'