我的方法是这样的:
import socket
REMOTE_SERVER = "one.one.one.one"
def is_connected(hostname):
try:
# see if we can resolve the host name -- tells us if there is
# a DNS listening
host = socket.gethostbyname(hostname)
# connect to the host -- tells us if the host is actually
# reachable
s = socket.create_connection((host, 80), 2)
s.close()
return True
except:
pass
return False
%timeit is_connected(REMOTE_SERVER)
> 10 loops, best of 3: 42.2 ms per loop
如果没有连接(OSX,Python 2.7),它将在不到一秒钟的时间内返回。
注意:此测试可能会返回误报- 例如,DNS查找可能会返回本地网络中的服务器。为确保您已连接到Internet并与有效的主机通信,请确保使用更复杂的方法(例如SSL)。