Wandering Thoughts archives

2005-12-03

How to do TCP keepalives in Python

TCP keepalives are do-nothing packets the TCP layer can send to see if a connection is still alive or if the remote end has gone unreachable (due to a machine crash, a network problem, or whatever). Keepalives are not default TCP behavior (at least not in any TCP stack that conforms to the RFCs), so you have to specifically turn them on. (There are various reasons why this is sensible.)

In Python you can do this with the .setsockopt() socket method, using the socket.SO_KEEPALIVE option and setting a value of integer 1. The only mystery is what the level parameter should be; despite what you might guess, it is socket.SOL_SOCKET. So a complete code example is:

import socket
def setkeepalives(sck):
  sck.setsockopt(socket.SOL_SOCKET, \
                 socket.SO_KEEPALIVE, 1)

Various sources recommend turning keepalives on as soon as possible after you have the socket.

(Keepalives are only applicable to TCP sockets, so one might expect SOL_TCP or at least SOL_IP, but no; they are a generic socket level option. Go figure.)

On Linux, you can control various bits of keepalive behavior by setting the additional SOL_TCP integer parameters TCP_KEEPIDLE, TCP_KEEPINTVL, and TCP_KEEPCNT; Python defines them all in the socket module. See the tcp(7) manpage for details. The default values are found in /proc/sys/net/ipv4 in the files tcp_keepalive_time, tcp_keepalive_intvl, and tcp_keepalive_probes, and are fairly large.

TcpKeepalivesInPython written at 03:17:29; Add Comment


Page tools: See As Normal.
Search:
Login: Password:
Atom Syndication: Recent Pages, Recent Comments.

This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.