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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值