One thing a lot of the answers miss is that (at least in Windows) the ping
command returns 0 (indicating success) if it receives the reply "Destination host unreachable."
Here is my code that checks if b'TTL='
is in the response, since that is only present when the ping reached the host. Note: Most of this code is based on the other answers here.
import platform
import subprocess
def ping(ipAddr, timeout=100):
'''
Send a ping packet to the specified host, using the system ping command.
Accepts ipAddr as string for the ping destination.
Accepts timeout in ms for the ping timeout.
Returns True if ping succeeds otherwise Returns False.
Ping succeeds if it returns 0 and the output includes b'TTL='
'''
if platform.system().lower() == 'windows':
numFlag = '-n'
else:
numFlag = '-c'
completedPing = subprocess.run(['ping', numFlag, '1', '-w', str(timeout), ipAddr],
stdout=subprocess.PIPE, # Capture standard out
stderr=subprocess.STDOUT) # Capture standard error
# print(completedPing.stdout)
return (completedPing.returncode == 0) and (b'TTL=' in completedPing.stdout)
print(ping('google.com'))
Note: This captures the output instead of printing it, so if you want to see the output of ping
, you'll need to print completedPing.stdout
before returning.