如何检查是否有互联网连接

时间:2019-04-12 10:17:21

标签: python python-3.x sockets urllib

我必须检查我的计算机是否已连接到互联网(因此,如果我打开浏览器,我可以还是不能访问URL),为此我尝试使用一些代码进行了尝试:

第一个是

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

    except Exception as e:
        print(e)
        print("internet off.")
        return False
internet_on()
我从此答案Checking internet connection with Python 中获取的

代码

我尝试了以下方法:

from urllib.request import urlopen
def internet_on():
        try:
            urlopen("https://www.instagram.com/", timeout=5)
            return True
        except Exception as err:
            print(str(err))
            return False
internet_on()
我从此答案Checking network connection中获取的

代码

还有这个

import socket
REMOTE_SERVER = "www.google.com"
def internet_on(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)
            return True
      except Exception:
            return False
internet_on(REMOTE_SERVER)
我从此答案Test if an internet connection is present in python 中获取的

代码

如果连接处于活动状态,则代码可以正常工作 但是当没有连接时,所有这些代码都会引发相同的错误:

Traceback (most recent call last):
  File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\urllib3\connection.py", line 159, in _new_conn
    (self._dns_host, self.port), self.timeout, **extra_kw)
  File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\urllib3\util\connection.py", line 57, in create_connection
    for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM):
  File "C:\Program Files\Python37-32\lib\socket.py", line 748, in getaddrinfo
    for res in _socket.getaddrinfo(host, port, family, type, proto, flags):
socket.gaierror: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\urllib3\connectionpool.py", line 600, in urlopen
    chunked=chunked)
  File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\urllib3\connectionpool.py", line 343, in _make_request
    self._validate_conn(conn)
  File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\urllib3\connectionpool.py", line 839, in _validate_conn
    conn.connect()
  File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\urllib3\connection.py", line 301, in connect
    conn = self._new_conn()
  File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\urllib3\connection.py", line 168, in _new_conn
    self, "Failed to establish a new connection: %s" % e)
urllib3.exceptions.NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x03B39E90>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\requests\adapters.py", line 449, in send
    timeout=timeout
  File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\urllib3\connectionpool.py", line 638, in urlopen
    _stacktrace=sys.exc_info()[2])
  File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\urllib3\util\retry.py", line 398, in increment
    raise MaxRetryError(_pool, url, error or ResponseError(cause))
urllib3.exceptions.MaxRetryError: HTTPSConnectionPool(host='www.instagram.com', port=443): Max retries exceeded with url: /_exploreurself (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x03B39E90>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:/Users/mcara/OneDrive/Desktop/file InstaBot da editare/v0.4/bot.py", line 835, in <module>
    bot.unfollow_process(RANDOM, sense=UP_DOWN, following_target=0, sleep_time=60)
  File "C:/Users/mcara/OneDrive/Desktop/file InstaBot da editare/v0.4/bot.py", line 651, in unfollow_process
    current_following = self.user_following_num(self._username)
  File "C:/Users/mcara/OneDrive/Desktop/file InstaBot da editare/v0.4/bot.py", line 387, in user_following_num
    r = requests.get(url).text
  File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\requests\api.py", line 75, in get
    return request('get', url, params=params, **kwargs)
  File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\requests\api.py", line 60, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\requests\sessions.py", line 533, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\requests\sessions.py", line 646, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\mcara\PycharmProjects\1\venv\lib\site-packages\requests\adapters.py", line 516, in send
    raise ConnectionError(e, request=request)
requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.instagram.com', port=443): Max retries exceeded with url: /_exploreurself (Caused by NewConnectionError('<urllib3.connection.VerifiedHTTPSConnection object at 0x03B39E90>: Failed to establish a new connection: [Errno 11001] getaddrinfo failed'))

2 个答案:

答案 0 :(得分:1)

尝试使用库 'subprocess' www.google.com 运行 ping > ,下面是代码示例。此解决方案是间接的,但有时最好在系统命令中委派以完成诸如此类的某些工作。

import subprocess
def my_dir(my_path):
    output=''
    try:
        p = subprocess.Popen('ping '+my_path, stdout = subprocess.PIPE, stderr = subprocess.STDOUT,
        #close_fds = True, #not valid for Windows platforms
        shell = True
        )
        output, err = p.communicate()
        #print(output)

    finally:
        if p is not None:
            try: p.kill()
            except: pass
    return output


print(my_dir('www.google.com'))

Ping example (running external command)

然后,您可以解析其输出以了解您是否已到达Google的服务器。

答案 1 :(得分:1)

在此处尝试使用此IP地址216.58.192.142是Google的IP地址之一。由于IP地址是静态的,因此该代码不够可靠,因此可能无法始终正常运行,因此,请使用您认为响应速度更快的其他网站替换该IP地址。

代码使用固定IP地址而不是完全限定域名(FQDN)的原因是因为FQDN需要进行DNS查找。当计算机没有可用的Internet连接时,DNS查找本身可能会阻止对urllib_request.urlopen的调用超过一秒钟。

import urllib2

def internet_on():
    try:
        urllib2.urlopen('http://216.58.192.142', timeout=1)
        return True
    except urllib2.URLError as err: 
        return False
相关问题