【问题标题】:Check internet connection availability with connected wifi in python在 python 中使用连接的 wifi 检查互联网连接可用性
【发布时间】:2021-03-26 17:01:10
【问题描述】:

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

设置:
我有一个 Pi4 并正在运行 Raspap,以打开一个热点,我可以通过静态 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()”函数看起来像其中之一(它们的末尾有一个数字,用于测试不同的方式):


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 路由器(没有互联网连接),但无论我使用上述什么功能,我总是得到 True。

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

非常感谢!

最好的 汗iii

【问题讨论】:

    标签: python


    【解决方案1】:

    这可能会对你有所帮助。

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

    【讨论】:

    • 嗨,谢谢,我也试过这个。我试过 request.head(..) 也试过 request.get(...) 但仍然得到相同的结果,它连接到互联网,虽然它不是
    • 尝试下载一个临时文件。例如“facebook.com/favicon.ico”。然后检查它是否在下载路径中。我相信它会解决你的问题。
    【解决方案2】:

    您可以测试对 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
    [[]]
    

    【讨论】:

      猜你喜欢
      • 2018-02-02
      • 1970-01-01
      • 2023-04-03
      • 1970-01-01
      • 2014-10-13
      • 1970-01-01
      • 1970-01-01
      • 2015-01-02
      • 1970-01-01
      相关资源
      最近更新 更多