Local network pinging in python

Justin Gardner picture Justin Gardner · Oct 6, 2011 · Viewed 35.3k times · Source

Does anyone know how to use python to ping a local host to see if it is active or not? We (my team and I) have already tried using

os.system("ping 192.168.1.*") 

But the response for destination unreachable is the same as the response for the host is up.

Thanks for your help.

Answer

Avi Mehenwal picture Avi Mehenwal · Feb 19, 2013

Use this ...

import os

hostname = "localhost" #example
response = os.system("ping -n 1 " + hostname)

#and then check the response...
if response == 0:
    print(hostname, 'is up!')
else:
    print(hostname, 'is down!')

If using this script on unix/Linux replace -n switch with -c !
Thats all :)