测试python中是否存在互联网连接 [英] Test if an internet connection is present in python

查看:83
本文介绍了测试python中是否存在互联网连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码来检查是否存在Internet连接.

I have the following code that checks if an internet connection is present.

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

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

This will test for an internet connection, but how effective is it?

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

I know internet varies in quality from person to person, so I'm looking for something that is most effective for the broad spectrum, and the above code seems like there might be loopholes where people could find bugs. For instance if someone just had a really slow connection, and took longer than 20 seconds to respond.

推荐答案

我的方法将是这样的:

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

这篇关于测试python中是否存在互联网连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆