I am working on python project where I need to ping an ip address
to check if it online or offline. For this I have referred to most of the questions and answers online. Below is what I have tried first:
response = os.system("ping -c 1 " + ip_address)
if response == 0:
print("Online")
else:
print("Offline")
Above approach works fine but if we have Reply from <ip>. Destination host unreachable
, then also it says Online
when in actual it should be Offline
.
Another solution I tried is checking the output of ping command:
cmd = "ping -c 1 " + ip_address
res = (subprocess.check_output(cmd, shell=True))
res = res.decode("utf-8")
if 'unreachable' in res or 'timed out' in res or '100% packet loss' in res:
print("Offline")
else:
print("Online")
In this approach I am checking if the response contains unreachable
or timed out
or 100% packet loss
(only in case of linux), then I am saying that its Offline
or else Online
. This solution works well in all cases but sometime it throws error Command 'ping -c 1 <ip>' returned non-zero exit status 1.
I also need to make sure that code I am writing should work both on Windows
and Ubuntu
.
I am not able to understand on what is the cleanest and simplest way of checking the response of ping and deciding if Online
or Offline
. Can anyone please help me. Thanks