您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

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

我的方法是这样的:

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)。

python 2022/1/1 18:41:45 有424人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶