我需要快速检查主机是否启动或关闭。为此,我在建立连接之前添加了套接字超时,但套接字超时似乎不起作用。为什么?
这是我的代码:
import socket
def test_hostname(hostname, port):
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.settimeout(1.0) # timeout
try:
s.connect((hostname, port))
except (socket.timeout, socket.gaierror):
return False
else:
return True
finally:
s.close()
result = test_hostname("001.com",80) # 001.com is down
print(result)
Run Code Online (Sandbox Code Playgroud)
我花了大约 10-20 秒而不是指定的超时(1 秒)。