【问题标题】:Checking internet connection with Python使用 Python 检查互联网连接
【发布时间】:2023-04-03 15:06:01
【问题描述】:

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

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。

【问题讨论】:

  • this post 回答你的问题了吗?
  • 这篇文章没有回答我的问题,我已经看到了

标签: python


【解决方案1】:

你应该做类似的事情

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

甚至更好(主要取自 cmets 中链接的其他答案)

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

【讨论】:

  • 你能解释一下你在我使用的函数中添加的这一行吗?
  • 为什么要测试四次,每次多五毫秒?
【解决方案2】:

您也可以使用另一个库来执行此操作。如果您要提取任何内容,我强烈建议您使用 Requests。

Joran 有一个很好的答案,它绝对有效。另一种方法是:

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

尝试并在错误发生时处理错误总是比重复进行不必要的检查要快。

【讨论】:

    【解决方案3】:

    我建议你使用 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
    

    【讨论】:

      【解决方案4】:

      兄弟,这是ez,请执行以下操作: 做一个Def函数并把它放进去

      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:
          print ("internet off.")
      

      【讨论】:

      • 如果我删除 s.close() ,它会像监听器一样工作吗?
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-15
      • 2017-03-16
      相关资源
      最近更新 更多