简体   繁体   English

在 python 中使用已连接的 wifi 检查互联网连接可用性

[英]Check internet connection availability with connected wifi in python

I hope I can find some help here.我希望我能在这里找到一些帮助。 After searching for possibilities to "check whether an internet connection is available with python" I found various way to perform that check.在搜索了“检查 python 是否可以使用 Internet 连接”的可能性后,我找到了执行该检查的各种方法。 However, those proposed ways does not work for me and I have no clue, why it doesn't so I am seeking for some advice.但是,这些建议的方法对我不起作用,我不知道为什么不起作用,所以我正在寻求一些建议。

The setup:设置:
I have a Pi4 and running Raspap, to open up a Hotspot, which I can access via a static IP address.我有一个 Pi4 并正在运行 Raspap,以打开一个热点,我可以通过 static IP 地址访问该热点。 Raspap is configured to connect to a wifi LTE router to get internet connectivity. Raspap 配置为连接到 wifi LTE 路由器以获得互联网连接。 I am using this Pi4 in a headless mode and using Raspap to access the Pi or to configure a different Wifi network than the wifi LTE router one.我在无头模式下使用这个 Pi4,并使用 Raspap 访问 Pi 或配置与 wifi LTE 路由器不同的 Wifi 网络。

I have a python script running to check for files in a folder and upload them to a cloud service, if a internet connection is available and renames the files afterwards.我有一个 python 脚本正在运行以检查文件夹中的文件并将它们上传到云服务,如果互联网连接可用,然后重命名文件。 Before I have setup Raspap, the Pi was only connected to a wifi or not and my check for internet connectivity was working.在我设置 Raspap 之前,Pi 是否仅连接到 wifi,并且我对互联网连接的检查工作正常。

The scenario:场景:
The mobile LTE router does not have a SIM card inserted, so the PI4 is connected to the mobile LTE routers wifi, but there is no internet access.移动LTE路由器没有插入SIM卡,所以PI4连接到移动LTE路由器wifi,但无法上网。 In this case the python script should recognize, that there is no internet connectivity and does not upload any files.在这种情况下,python 脚本应该识别出没有互联网连接并且不上传任何文件。 However, the if condition for the wifi check is still true, of course the upload is not working, but the script performs the renaming afterwards.但是,wifi检查的if条件仍然为真,当然上传不起作用,但脚本会在之后执行重命名。

The python script for uploading and renaming looks like this:用于上传和重命名的 python 脚本如下所示:

def upload():
    # run a function to check a folder for files without a "X_" prefix and put it to an uploadQueue (as an global array)
    retrieveFilesForUpload(uploadFolder, 60, olderThanXDays=olderThanXDays)
    
    # if upload queue contains files and  the Pi is connected to the internet, then upload the files
    if len(uploadQueue)>0 and isConnectedToInternet():
        # the retrieveAndUpload function uses the global array as input
        upload = threading.Thread(target=retrieveAndUpload)
        upload.start()
        upload.join()

        # after uploading the file, rename it by adding a Prefix "X_" 
        renameUploadedFiles(uploadFolder)

The "isConnectedToInternet()" function looks like one of these (they have a number at the end for testing the different ways): “isConnectedToInternet()” function 看起来像其中之一(它们的末尾有一个数字用于测试不同的方式):


def isConnectedWithInternet0():
    try:
        socket.create_connection(("1.1.1.1", 53))
        return True
    except OSError:
        pass
    return False

def isConnectedWithInternet2():
    for timeout in [1, 5, 10, 15]:
        print("timeout:", timeout)
        try:
            socket.setdefaulttimeout(timeout)
            host = socket.gethostbyname("www.google.com")
            s = socket.create_connection((host, 443), 2)
            s.close()
            print("Internet connection available")
            return True
        except OSError:
            print("No Internet")
            pass
    return False

def isConnectedWithInternet():
    import requests
    timeout = 2
    url = "http://8.8.8.8"
    try: 
        request = requests.head(url, timeout=timeout)
        print("Function 3: Connected to internet")
        return True
    except (requests.ConnectionError, requests.Timeout) as exception:
        print("Function 3: no Internet")
        return False

def isConnectedWithInternet4():
    host = "8.8.8.8"
    port = 53
    result = ""
    try:
        socket.setdefaulttimeout(2)
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect((host, port))
        #return True
    except socket.error as ex:
        print(ex)
        return False
    else:
        s.close()
        return True
    #return result

def isConnectedWithInternet5():
    import urllib.request
    try: 
        urllib.request.urlopen("http://216.58.192.142", timeout=1)
        return True
    except urllib.request.error as err:
        print(err)
        return False

def isConnectedWithInternet6():
    try:
        import httplib
    except:
        import http.client as httplib

    timeout = 2
    url = "www.google.com"
    conn = httplib.HTTPConnection(url, timeout=timeout)
    try:
        conn.request("HEAD", "/")
        conn.close()
        return True
    except Exception as e:
        print(e)
        return False

But although the Wifi is connected to a wifi LTE router with no SIM card inserted (there is no internet connection), I always get True as a result, no matter what function above I am using.但是,尽管 Wifi 连接到没有插入 SIM 卡的 wifi LTE 路由器(没有互联网连接),但无论我使用什么上面的 function,我总是得到 True。

I hope somebody can give me a hint/advice/some help on this issue.我希望有人可以在这个问题上给我一个提示/建议/一些帮助。

Thank you very much!非常感谢!

Best Khaniii最好的可汗

This may help you.这可能会对您有所帮助。

import requests

url = "http://www.google.com"
timeout = 5
try:
    request = requests.get(url, timeout=timeout)
    print("Connected to the Internet")
except (requests.ConnectionError, requests.Timeout) as exception:
    print("No internet connection.")

You can test ping to an internet server.您可以测试对 Internet 服务器的 ping。 This worked for me while monitoring my internet connexion:这在监控我的互联网连接时对我有用:

import platform    # For getting the operating system name
import subprocess  # For executing a shell command
import re

def ping(host):
    results = []
    param = '-n' if platform.system().lower()=='windows' else '-c'
    command = ['ping', param, '1', host]
    output = subprocess.Popen(command, stdout=subprocess.PIPE).stdout.read()
    result = re.findall("=\ (\d+)ms", str(output))
    results.append(result)
    return results

ping('8.8.8.8')

this returns the ping values in a list or empty list if no ping answer如果没有 ping 答案,这将返回列表中的 ping 值或空列表

[['6', '6', '6']]
or
[[]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM