簡體   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