【整理】Python如何保持TCP心跳

原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: 【整理】Python如何保持TCP心跳

参考:How to change tcp keepalive timer using python script?

参考:https://delog.wordpress.com/2013/08/16/handling-tcp-keepalive/

您可以使用setsockopt()在已经打开的套接字上设置TCP keepalive定时器。

import socket

def set_keepalive_linux(sock, after_idle_sec=1, interval_sec=3, max_fails=5):
    """Set TCP keepalive on an open socket.

    It activates after 1 second (after_idle_sec) of idleness,
    then sends a keepalive ping once every 3 seconds (interval_sec),
    and closes the connection after 5 failed ping (max_fails), or 15 seconds
    """
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
    sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPIDLE, after_idle_sec)
    sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPINTVL, interval_sec)
    sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_KEEPCNT, max_fails)

def set_keepalive_osx(sock, after_idle_sec=1, interval_sec=3, max_fails=5):
    """Set TCP keepalive on an open socket.

    sends a keepalive ping once every 3 seconds (interval_sec)
    """
    # scraped from /usr/include, not exported by python's socket module
    TCP_KEEPALIVE = 0x10
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)
    sock.setsockopt(socket.IPPROTO_TCP, TCP_KEEPALIVE, interval_sec)

如果用上面的代码针对windows下的python socket进行设置,可能会发生如下错误:

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'

针对windows下的python socket tcp keepalive设置,可以这么设置,更多信息参考:https://msdn.microsoft.com/en-us/library/dd877220%28v=vs.85%29.aspx

sock.ioctl(socket.SIO_KEEPALIVE_VALS, (1, 10000, 3000))
原创文章,转载请注明: 转载自勤奋的小青蛙
本文链接地址: 【整理】Python如何保持TCP心跳

文章的脚注信息由WordPress的wp-posturl插件自动生成



|2|left
打赏

发表评论

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: