且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

测试python中是否存在互联网连接

更新时间:2023-01-01 18:18:49

我的方法将是这样的:

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),则将在不到一秒钟的时间内返回.

This will return within less than a second if there is no connection (OSX, Python 2.7).

注意:此测试可能返回假阳性-例如DNS查找可能会返回本地网络中的服务器.为确保您已连接到互联网并与有效的主机进行通话,请确保使用更复杂的方法(例如SSL).

Note: This test can return false positives -- e.g. the DNS lookup may return a server within the local network. To be really sure you are connected to the internet, and talking to a valid host, be sure to use more sophisticated methods (e.g. SSL).