Python Forum
testing for a network connection
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
testing for a network connection
#3
Quote:what's the simplest way to test if it is a network connection that is connected?

I had done this kind of task.
Situation: There is a device, which connects to wifi, then it should check if the device can reach the default gateway (router IP) or if it's in "online-mode", it should check a known IP in internet.

This was my preparation to obtain local IPs and the gateway IP with two different solutions.
One solution is using iproute2 (ip command, which can return json) or netifaces which works also on Windows.

Code: https://pastebin.com/yqcAQGyh


Example code which works only on my machine ^^
import json
from socket import gethostbyname, gaierror
from subprocess import check_output, call, DEVNULL


OK = "✓"
FAIL = "✗"


def get_default_gateways():
    cmd = ["ip", "-j", "-4", "r", "s", "default"]
    result = json.loads(check_output(cmd, encoding="utf8"))
    return [res.get("gateway", "") for res in result]


def ping_ip(ip):
    return call(["ping", "-c1", "-W1", ip], stdout=DEVNULL, stderr=DEVNULL) == 0


def check_dns():
    try:
        gethostbyname("google.com")
    except OSError:
        return False
    else:
        return True


if __name__ == "__main__":
    result = False
    gateways = get_default_gateways()
    if gateways:
        result = ping_ip(gateways[0])
    if result:
        print(f"[{OK}] Gateway")
    else:
        print(f"[{FAIL}] Gateway")

    if ping_ip("1.1.1.1"):
        print(f"[{OK}] Internet")
    else:
        print(f"[{FAIL}] Internet")

    if check_dns():
        print(f"[{OK}] DNS")
    else:
        print(f"[{FAIL}] DNS")
Obviously I'm online:
Output:
[✓] Gateway [✓] Internet [✓] DNS
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply


Messages In This Thread
testing for a network connection - by Skaperen - Jun-16-2020, 01:02 AM
RE: testing for a network connection - by DeaD_EyE - Jun-16-2020, 05:12 PM
RE: testing for a network connection - by Skaperen - Jun-16-2020, 10:34 PM
RE: testing for a network connection - by DeaD_EyE - Jun-17-2020, 09:32 AM

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020