Pinging servers in Python


Question

In Python, is there a way to ping a server through ICMP and return TRUE if the server responds, or FALSE if there is no response?

1
142
6/1/2010 9:27:21 PM

If you don't need to support Windows, here's a really concise way to do it:

import os
hostname = "google.com" #example
response = os.system("ping -c 1 " + hostname)

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

This works because ping returns a non-zero value if the connection fails. (The return value actually differs depending on the network error.) You could also change the ping timeout (in seconds) using the '-t' option. Note, this will output text to the console.

143
5/1/2012 6:29:04 PM

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon