The Python Oracle

Pinging servers in Python

This video explains
Pinging servers in Python

--

Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Meditation

--

Chapters
00:00 Question
00:21 Accepted answer (Score 194)
01:47 Answer 2 (Score 207)
02:20 Answer 3 (Score 56)
02:49 Answer 4 (Score 35)
03:00 Thank you

--

Full question
https://stackoverflow.com/questions/2953...

Accepted answer links:
[@radato]: https://stackoverflow.com/users/797396/r...
[shell injection]: https://en.wikipedia.org/wiki/Shell_inje...
[platform.system()]: https://docs.python.org/library/platform...
[subprocess.call()]: https://docs.python.org/library/subproce...

Answer 3 links:
[pyping]: https://pypi.org/pypi/pyping/

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3.x #ping #icmp



ANSWER 1

Score 227


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

import os
param = '-n' if os.sys.platform().lower()=='win32' else '-c'
hostname = "google.com" #example
response = os.system(f"ping {param} 1 {hostname}")

#and then check the response...
if response == 0:
  print(f"{hostname} is up!")
else:
  print(f"{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.




ACCEPTED ANSWER

Score 209


This function works in any OS (Unix, Linux, macOS, and Windows)
Python 2 and Python 3

EDITS:
By @radato os.system was replaced by subprocess.call. This avoids shell injection vulnerability in cases where your hostname string might not be validated.

import platform    # For getting the operating system name
import subprocess  # For executing a shell command

def ping(host):
    """
    Returns True if host (str) responds to a ping request.
    Remember that a host may not respond to a ping (ICMP) request even if the host name is valid.
    """

    # Option for the number of packets as a function of
    param = '-n' if platform.system().lower()=='windows' else '-c'

    # Building the command. Ex: "ping -c 1 google.com"
    command = ['ping', param, '1', host]

    return subprocess.call(command) == 0

Note that, according to @ikrase on Windows this function will still return True if you get a Destination Host Unreachable error.

Explanation

The command is ping in both Windows and Unix-like systems.
The option -n (Windows) or -c (Unix) controls the number of packets which in this example was set to 1.

platform.system() returns the platform name. Ex. 'Darwin' on macOS.
subprocess.call() performs a system call. Ex. subprocess.call(['ls','-l']).




ANSWER 3

Score 58


There is a module called pyping that can do this. It can be installed with pip

pip install pyping

It is pretty simple to use, however, when using this module, you need root access due to the fact that it is crafting raw packets under the hood.

import pyping

r = pyping.ping('google.com')

if r.ret_code == 0:
    print("Success")
else:
    print("Failed with {}".format(r.ret_code))



ANSWER 4

Score 43


For python3 there's a very simple and convenient python module ping3: (pip install ping3, needs root privileges).

from ping3 import ping, verbose_ping
ping('example.com')  # Returns delay in seconds.
>>> 0.215697261510079666

This module allows for the customization of some parameters as well.