测试python中是否存在internet连接

2024-05-21 04:04:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码检查是否存在internet连接。

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

这将测试互联网连接,但它有多有效?

我知道互联网的质量因人而异,所以我在寻找对广谱网络最有效的东西,上面的代码似乎有漏洞,人们可能会发现漏洞。例如,如果某人的连接速度非常慢,并且需要20秒以上的时间才能做出响应。


Tags: 代码importtruehttpreturnonresponsedef
3条回答

从Python2.6和更新版本(包括Python3)开始,一个更直接的解决方案也与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

它解析名称,并尝试连接到每个返回addres,然后再断定其脱机。这还包括IPv6地址。

这样就行了

import urllib
try :
    stri = "https://www.google.co.in"
    data = urllib.urlopen(stri)
    print "Connected"
except e:
    print "not connected" ,e 

我的方法是这样的:

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

如果没有连接(OSX,Python2.7),这将在不到一秒钟内返回。

注意:此测试可能返回误报——例如,DNS查找可能返回本地网络中的服务器。为了确保您已连接到internet,并与有效的主机交谈,请确保使用更复杂的方法(例如SSL)。

相关问题 更多 >