本文介绍了如何使用python脚本更改tcp keepalive计时器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的 python 脚本中,我使用以下命令激活了 TCP Keepalive:

In my python script, I have activate TCP Keepalive using this command:

x = s.setsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1)

我的目标是关闭套接字连接,如果 5 分钟没有传输(*).我在 Windows 上工作,我的 python 脚本只接收而不向客户端程序传输任何数据.

My goal is for socket connection to get closed, if there is no transmission(*) for 5 minutes. I am working on Windows and my python script is only receiving and not transmitting any data to client program.

我所知道的是,默认情况下,如果 2 小时内没有传输,那么只有我可以使用 try 和 except 关闭连接.我知道,对于 Windows,我可以通过转到注册表来手动减少此等待时间.但是有没有办法可以从我的脚本中修改它?

What I know is, by default, if no transmission will be there for 2 hours, then only I can close the connection using try and except. I know, for windows, I can manually reduce this waiting time by going to registry. But is there is a way by which, I can modify it from my script?

(*) 此处无传输"的意思是某物悄悄地吃掉网络上的数据包",而不是我不想发送任何东西".

(*) here "no transmission" means "something quietly eats packets on the network" rather than "I'm not trying to send anything."

推荐答案

您可以使用 setsockopt() 在已打开的套接字上设置 TCP 保持活动计时器.

You can set the TCP keepalive timers on an already-open socket using setsockopt().

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 的等效选项 请参阅 msdn.查看Python源,似乎您需要设置SO_KEEPALIVEsock.setsockopt 类似在 Unix 中,并且[可选?] 设置 SIO_KEEPALIVE_VALSsock.ioctl.

For equivalent options on windows refer to msdn.Looking through the Python source, it seems you need to set SO_KEEPALIVE with sock.setsockopt similar to in Unix, and [optionally?] set SIO_KEEPALIVE_VALS with sock.ioctl.

这篇关于如何使用python脚本更改tcp keepalive计时器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 07:44