测试python中是否存在互联网连接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20913411/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:32:13  来源:igfitidea点击:

Test if an internet connection is present in python

pythonpython-2.7networking

提问by Joshua Strot

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?

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

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.

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

采纳答案by miraculixx

My approach would be something like this:

我的方法是这样的:

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

This will return within less than a second if there is no connection (OSX, Python 2.7).

如果没有连接(OSX,Python 2.7),这将在不到一秒的时间内返回。

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

注意:此测试可能会返回误报——例如,DNS 查找可能会返回本地网络中的服务器。要真正确定您已连接到 Internet 并与有效主机通话,请务必使用更复杂的方法(例如 SSL)。

回答by Micha? Tabor

Increase timeout to 30 seconds? Do multiple tries? Try few hosts?

将超时增加到 30 秒?多试几次?尝试几个主机?

回答by mpromonet

Http seems a too high level for checking network availability.

Http 似乎对于检查网络可用性来说太高了。

Nevertheless you can create a thread that check periodically the connectivity and store the connectivity state, next the internet_on method could just check the stored state. This will should be quicker than testing connectivity each time.

尽管如此,您可以创建一个线程来定期检查连接并存储连接状态,接下来 internet_on 方法可以只检查存储的状态。这应该比每次测试连接都快。

回答by ibrahim haleem khan

this will work

这会起作用

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

回答by user134355

This is what I use:

这是我使用的:

import subprocess

subprocess.call('ping -t 8.8.8.8')

回答by Jabba

I wanted to test my internet connection in an infinite loop to monitor when my network goes up and down. I noticed the following: when my network was down and I started the monitoring script like that and the network came back, the script didn't notice it. The network was alive but the script didn't see that. When my network was on and I started the script like that, it noticed the changes. So I came up with the following solution that worked for me in both cases:

我想无限循环地测试我的互联网连接,以监控我的网络何时起起伏伏。我注意到以下几点:当我的网络出现故障并且我像这样启动监控脚本并且网络恢复时,脚本没有注意到它。网络还活着,但脚本没有看到。当我的网络打开并且我像这样启动脚本时,它注意到了这些变化。所以我想出了以下在两种情况下都对我有用的解决方案:

import shlex
from subprocess import call, PIPE, STDOUT

def get_return_code_of_simple_cmd(cmd, stderr=STDOUT):
    """Execute a simple external command and return its exit status."""
    args = shlex.split(cmd)
    return call(args, stdout=PIPE, stderr=stderr)

def is_network_alive():
    cmd = "ping -c 1 www.google.com"
    return get_return_code_of_simple_cmd(cmd) == 0

Here we rely on an external program (ping) that is independent from our script.

在这里,我们依赖于ping独立于我们的脚本的外部程序 ( )。

回答by siczones

I hope ,I can help problem with you.

我希望,我可以帮助你解决问题。

import urllib
try :
    url = "https://www.google.com"
    urllib.urlopen(url)
    status = "Connected"
except :
    status = "Not connect"
print status

回答by andrebrait

As of Python 2.6 and newer (including Python 3), a more straightforward solution which is also compatible with IPv6 would be

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

It resolves the name and tries to connect to each return addres before concluding it is offline. This also includes IPv6 addresses.

它解析名称并尝试连接到每个返回地址,然后得出它是离线的。这也包括 IPv6 地址。

回答by Viraj Mohite

Though the answer has been ticked, it couldn't help me, I had getting an error like

虽然答案已被勾选,但它对我没有帮助,我收到了一个错误,如

urllib2 is undefined

urllib2 未定义

so I had tried to install urllib2library using pip but was helpless then I dig up around and luckily I got a solution please check following code, sharing because someone who will face problem that I had before, will get the solution

所以我曾尝试使用 pip安装urllib2库,但很无助,然后我四处寻找,幸运的是我得到了一个解决方案,请检查以下代码,分享因为有人会遇到我以前遇到的问题,会得到解决方案

from urllib.request import urlopen

def is_internet_available():
    try:
        urlopen('http://216.58.192.142', timeout=1)
        return True
    except:
        return False


print(is_internet_available())

回答by Soum Axetuirk

I don't need the post on every time check...So I use to notify when device goes from online to offline and vice versa.

我不需要每次检查都发帖......所以我用来通知设备何时从在线变为离线,反之亦然。

import socket
import time

mem1 = 0
while True:
    try:
        host = socket.gethostbyname(
            "www.google.com"
        )  # Change to personal choice of site
        s = socket.create_connection((host, 80), 2)
        s.close()
        mem2 = 1
        if mem2 == mem1:
            pass  # Add commands to be executed on every check
        else:
            mem1 = mem2
            print("Internet is working")  # Will be executed on state change

    except Exception as e:
        mem2 = 0
        if mem2 == mem1:
            pass
        else:
            mem1 = mem2
            print("Internet is down")
    time.sleep(10)  # timeInterval for checking