1

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

S Andrew
  • 5,592
  • 27
  • 115
  • 237
  • Just FYI in case you didn't already know, the `ping` command is different between the platforms. Not only the output but the flags etc as well. You'd do best to implement a "response function" that can divert the parsing to individual [platform specific](https://stackoverflow.com/questions/1387222/reliably-detect-windows-in-python) handlings. Otherwise you'll probably end up with a blob of if/else mess. And I think https://stackoverflow.com/questions/2502833/store-output-of-subprocess-popen-call-in-a-string is a better approach to using subprocess :) – Torxed May 22 '20 at 09:28
  • 2
    I'd personally go with sending raw icmp packages directly to avoid relying on command line .. https://github.com/alessandromaggio/pythonping looks ok for this sort of use - at least you can get the idea how its done if you cant rely on 3rd party libs. – rasjani May 22 '20 at 09:32
  • @rasjani It looks good but the response doesnt contain any attribute which can say weather the ping was success or failure. can you show a minimal example using this – S Andrew May 22 '20 at 10:15

1 Answers1

0

Check out the scapy python library.

The first example here would give you some insights on how to solve the ping problem.

pappachino
  • 35
  • 1
  • 5