I am using os.system ("ping 192.168.178.5") command to ping a machine. Funny thing is, I get exit code 0 even if ping fails.
How can I get something that tells me the ping failed/host is offline?
I am using os.system ("ping 192.168.178.5") command to ping a machine. Funny thing is, I get exit code 0 even if ping fails.
How can I get something that tells me the ping failed/host is offline?
I'm not a user of Python, but one can find a lot of material about this problem.
For example, the post Local network pinging in python contains two solutions that I reproduce here (not tested).
Solution 1 : Parsing the output of the ping command
import subprocess
hostname = "10.20.16.30"
output = subprocess.Popen(["ping.exe",hostname],stdout = subprocess.PIPE).communicate()[0]
print(output)
if ('unreachable' in output):
print("Offline")
One can also test this way for "Request timed out".
Solution 2 : Using a socket (adapted from original code so not guaranteed)
s = socket(AF_INET, SOCK_STREAM) # Creates socket
host = 'localhost' # Enter the IP of the workstation here
port = 80 # Select port which should be pinged
try:
s.connect((host, port)) # tries to connect to the host
except ConnectionRefusedError: # if failed to connect
print("Server offline") # server is offline
s.close() # close socket
The use of os.system ("ping 192.168.178.5")
command to ping a machine depends from the system on which you are.
From an online help for Ping under windows:
A successful PING does NOT always return an %errorlevel% of 0 Therefore to reliably detect a successful ping - pipe the output into FIND and look for the text "TTL"
So it seems you should use instead of ping 192.168.178.5
something like ping -n 1 192.168.178.5 | find "TTL="
From man ping
on Linux (System Manager's Manual: iputils)
If ping does not receive any reply packets at all it will exit with code 1. If a packet count and deadline are both specified, and fewer than count packets are received by the time the deadline has arrived, it will also exit with code 1. On other error it exits with code 2. Otherwise it exits with code 0. This makes it possible to use the exit code to see if a host is alive or not.
In this case you can use directly the exit code.