繁体   English   中英

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

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

我希望我能在这里找到一些帮助。 在搜索了“检查 python 是否可以使用 Internet 连接”的可能性后,我找到了执行该检查的各种方法。 但是,这些建议的方法对我不起作用,我不知道为什么不起作用,所以我正在寻求一些建议。

设置:
我有一个 Pi4 并正在运行 Raspap,以打开一个热点,我可以通过 static IP 地址访问该热点。 Raspap 配置为连接到 wifi LTE 路由器以获得互联网连接。 我在无头模式下使用这个 Pi4,并使用 Raspap 访问 Pi 或配置与 wifi LTE 路由器不同的 Wifi 网络。

我有一个 python 脚本正在运行以检查文件夹中的文件并将它们上传到云服务,如果互联网连接可用,然后重命名文件。 在我设置 Raspap 之前,Pi 是否仅连接到 wifi,并且我对互联网连接的检查工作正常。

场景:
移动LTE路由器没有插入SIM卡,所以PI4连接到移动LTE路由器wifi,但无法上网。 在这种情况下,python 脚本应该识别出没有互联网连接并且不上传任何文件。 但是,wifi检查的if条件仍然为真,当然上传不起作用,但脚本会在之后执行重命名。

用于上传和重命名的 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)

“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

但是,尽管 Wifi 连接到没有插入 SIM 卡的 wifi LTE 路由器(没有互联网连接),但无论我使用什么上面的 function,我总是得到 True。

我希望有人可以在这个问题上给我一个提示/建议/一些帮助。

非常感谢!

最好的可汗

这可能会对您有所帮助。

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

您可以测试对 Internet 服务器的 ping。 这在监控我的互联网连接时对我有用:

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

如果没有 ping 答案,这将返回列表中的 ping 值或空列表

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

暂无
暂无

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

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