Python socket.gethostbyaddr()不响应SIGINT

时间:2018-05-21 17:54:28

标签: python-3.x

$ nslookup 192.168.85.242

运行约20秒并失败。在20秒内的任何时间发送SIGINT(control-C)会导致命令立即结束。

另一方面,使用Python 3.6.4:

$ python
Python 3.6.4 (default, Jan 26 2018, 08:18:54)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-18)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import socket
>>> socket.gethostbyaddr("192.168.85.242")
^C

点击control-C什么都不做,套接字命令似乎决定不放弃。

我的问题是,为什么?最重要的是,如果我循环遍历多个IP地址并且我希望我的代码在2秒之后失败,那么实现超时的标准方法(例如https://pypi.org/project/timeout-decorator/和{{} 3}})不会工作。

2 个答案:

答案 0 :(得分:0)

尝试使用Ctrl + \代替SIGQUIT SIGINT。当CTRL + C失败时,它往往会杀死进程。

答案 1 :(得分:0)

我最终这样做了,出于某种原因,多处理模块具有" power"超时gethostbyaddr()方法。

@functools.lru_cache(maxsize=None)
def gethostbyaddr(ip_address):
    try:
        base.get_logger().debug(f"Looking up {ip_address} ...")
        hostname, _, _ = socket.gethostbyaddr(ip_address)
        return hostname
    except (Exception, ) as e:
        base.get_logger().debug(str(e) + " for " + ip_address)
        return None

# We need this pool/multiprocessing business so as to timeout after a couple of seconds
# if we are not going to get an answer
# See https://docs.python.org/3/library/multiprocessing.html#using-a-pool-of-workers
@functools.lru_cache(maxsize=None)
def get_host_name(ip_address):
    with multiprocessing.Pool(processes=1) as pool:
        try:
            result = pool.apply_async(gethostbyaddr, (ip_address, ))
            return result.get(timeout=2)
        except multiprocessing.context.TimeoutError:
            return None

在我的主要代码中,我有:

entry_dict[defs.DNS] = get_host_name(row[defs.IP])