import socket
socket.setdefaulttimeout(0.01)
socket.getaddrinfo("123123231", 12345)
这个setdefaulttimeout对socket模块方法没有用处,只是针对socket.socket对象设置超时。这点从源代码中可以看出。
def create_connection(address, timeout=_GLOBAL_DEFAULT_TIMEOUT,
source_address=None):
host, port = address
err = None
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
af, socktype, proto, canonname, sa = res
sock = None
try:
sock = socket(af, socktype, proto)
if timeout is not _GLOBAL_DEFAULT_TIMEOUT:
sock.settimeout(timeout)
if source_address:
sock.bind(source_address)
sock.connect(sa)
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 getaddrinfo(host, port, family=0, type=0, proto=0, flags=0):
addrlist = []
for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
af, socktype, proto, canonname, sa = res
addrlist.append((_intenum_converter(af, AddressFamily),
_intenum_converter(socktype, SocketKind),
proto, canonname, sa))
return addrlist
解决方案:(python3代码)
import socket
socket.setdefaulttimeout(0.01)
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
sock.connect(("123123231", 12345))
except socket.timeout as e:
print("timeout")
pass