使用Python检查互联网连接 - python

我正在使用互联网的应用程序上工作,因此我需要检查应用程序负载是否存在互联网连接,因此我使用以下功能:

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发送请求,但是这也花费了时间和超时。有更好的方法吗?我正在使用Windows 7和Python 2.6.6。

python大神给出的解决方案

你应该做类似的事情

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