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