用Python检查internet连接

2024-04-26 23:43:58 发布

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

我正在开发一个使用internet的应用程序,因此需要检查应用程序加载时是否有internet连接,因此我使用以下功能:

def is_connected():

    try:
        print "checking internet connection.."
        host = socket.gethostbyname("www.google.com")
        s = socket.create_connection((host, 80), 2)
        s.close()
        print 'internet on.'
        return True

    except Exception,e:
        print e
        print "internet off."
    return False

有时它会失败,尽管有互联网连接,它说'超时'。我还尝试使用urllib2向Google发送请求,但这需要时间,而且也超时了。有更好的办法吗?我使用的是Windows7和Python2.6.6。


Tags: 功能应用程序hostreturnisdefwwwsocket
3条回答

你应该做些

def check_internet():
    for timeout in [1,5,10,15]:
        try:
            print "checking internet connection.."
            socket.setdefaulttimeout(timeout)
            host = socket.gethostbyname("www.google.com")
            s = socket.create_connection((host, 80), 2)
            s.close()
            print 'internet on.'
            return True

        except Exception,e:
            print e
            print "internet off."
    return False

或者更好(大部分来自评论中的其他答案)

def internet_on():
    for timeout in [1,5,10,15]:
        try:
            response=urllib2.urlopen('http://google.com',timeout=timeout)
            return True
        except urllib2.URLError as err: pass
    return False

我建议您使用urllib。是预安装的库,不需要安装额外的库。 我的建议是:

def isConnected():
    import urllib
    from urllib import request
    try:
        urllib.request.urlopen('http://google.com') # If you want you can add the timeout parameter to filter slower connections. i.e. urllib.request.urlopen('http://google.com', timeout=5)

        return True
    except:
        return False

您也可以使用其他库来执行此操作。如果你需要任何内容,我强烈建议你使用请求。

乔兰有一个很好的答案,肯定有效。另一种方法是:

def checkNet():
    import requests
    try:
        response = requests.get("http://www.google.com")
        print "response code: " + response.status_code
    except requests.ConnectionError:
        print "Could not connect"

这样做的好处是您可以使用response对象并继续您的工作(response.text等)

与重复进行不必要的检查相比,尝试它并在错误出现时处理它总是更快。

相关问题 更多 >