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

Jos*_*rot 27 python networking python-2.7

我有以下代码检查是否存在互联网连接.

import urllib2

def internet_on():
    try:
        response=urllib2.urlopen('http://74.125.228.100',timeout=20)
        return True
    except urllib2.URLError as err: pass
    return False
Run Code Online (Sandbox Code Playgroud)

这将测试互联网连接,但效果如何?

我知道互联网的质量因人而异,所以我正在寻找对广谱来说最有效的东西,上面的代码似乎可能存在漏洞,人们可能会发现漏洞.例如,如果某人的连接速度非常慢,并且花了超过20秒的时间来响应.

mir*_*ixx 49

我的方法是这样的:

import socket
REMOTE_SERVER = "www.google.com"
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
Run Code Online (Sandbox Code Playgroud)

如果没有连接(OSX,Python 2.7),这将在不到一秒的时间内返回.

注意:此测试可能会返回误报 - 例如,DNS查找可能会返回本地网络中的服务器.要确定您已连接到互联网,并与有效的主机交谈,请务必使用更复杂的方法(例如SSL).

  • 不要使用“google.com”,而是使用“1.1.1.1”,它总是会更新,速度更快,而且不存在隐私问题。`1.1.1.1` 是 DNS 服务器,需要保持运行。也可以通过“one.one.one.one”访问“1.1.1.1” (4认同)
  • 这似乎是一个更好的方法。 (2认同)
  • 如果用户已将www.google.com添加到其/ etc/hosts文件中该怎么办?如果他们正在运行本地缓存名称服务器,或者在附近有缓存名称服务器的LAN上怎么办?如果他们"连接到互联网"但流量实际上没有正确路由怎么办?有很多方法可以让它失败. (2认同)
  • @ Jean-PaulCalderone公平点,包括实际的连接测试和相应的注释。如果认为合适,请随时改善答案 (2认同)

and*_*ait 14

从Python 2.6及更新版本(包括Python 3)开始,一个更简单的解决方案也将与IPv6兼容

import socket


def is_connected():
    try:
        # connect to the host -- tells us if the host is actually
        # reachable
        socket.create_connection(("www.google.com", 80))
        return True
    except OSError:
        pass
    return False
Run Code Online (Sandbox Code Playgroud)

它解析名称并尝试连接到每个返回地址,然后结束它是否脱机.这还包括IPv6地址.

  • 感谢您提供此解决方案 (2认同)

Pam*_*thi 6

检查互联网可用性的有效方法(修改后的@andrebrait 的答案)。

import socket

def isConnected():
    try:
        # connect to the host -- tells us if the host is actually
        # reachable
        sock = socket.create_connection(("www.google.com", 80))
        if sock is not None:
            print('Clossing socket')
            sock.close
        return True
    except OSError:
        pass
    return False
Run Code Online (Sandbox Code Playgroud)