Python Socket Connect 设置超时无效
胜博发娱乐手机版
胜博发娱乐手机版
当前位置 : 胜博发娱乐手机版 > 胜博发娱乐手机版

Python Socket Connect 设置超时无效

准备检测一个本地端口是否开放,设置了0.01秒超时,但是实际运行了10多秒才抛出异常。如何解决?

import socket
socket.setdefaulttimeout0.01
socket.getaddrinfo"123123231", 12345

setdefaulttimeout 是配置socket实例的

import socket
socket.setdefaulttimeout0.01
s=socket.socketsocket.AF_INET,socket.SOCK_STREAM
# 也可以在这设置
# s.settimeout0.01
s.connect"123123231", 12345
import socket
socket.setdefaulttimeout0.01 
socket.getaddrinfo"123123231", 12345

这个setdefaulttimeout对socket模块方法没有用处,只是针对socket.socket对象设置超时。这点从源代码中可以看出。

def create_connectionaddress, timeout=_GLOBAL_DEFAULT_TIMEOUT,
                      source_address=None:
    host, port = address
    err = None
    for res in getaddrinfohost, port, 0, SOCK_STREAM:
        af, socktype, proto, canonname, sa = res
        sock = None
        try:
            sock = socketaf, socktype, proto
            if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
                sock.settimeouttimeout
            if source_address:
                sock.bindsource_address
            sock.connectsa
            return sock

        except error as _:
            err = _
            if sock is not None:
                sock.close

    if err is not None:
        raise err
    else:
        raise error"getaddrinfo returns an empty list"
        
def getaddrinfohost, port, family=0, type=0, proto=0, flags=0:
    addrlist = []
    for res in _socket.getaddrinfohost, port, family, type, proto, flags:
        af, socktype, proto, canonname, sa = res
        addrlist.append_intenum_converteraf, AddressFamily,
                         _intenum_convertersocktype, SocketKind,
                         proto, canonname, sa
    return addrlist

解决方案:python3代码

import socket
socket.setdefaulttimeout0.01
sock = socket.socketsocket.AF_INET, socket.SOCK_STREAM
try:
    sock.connect"123123231", 12345
except socket.timeout as e:
    print"timeout"
    pass

广告位

胜博发娱乐手机版