Python Ping

  1. Ping Server in Python Using the subprocess.call() Method
  2. Ping Server in Python Using the os.system() Method
  3. Ping Server in Python Using the ping3.ping() Function

This tutorial will explain various methods to ping a server using Internet Control Message Protocol (ICMP) in Python. Ping is used to check if a particular server is available or not on an Internet Protocol. It measures the time it takes for a message to reach the destination (server) and for a server response to reach the source.

Ping Server in Python Using the subprocess.call() Method

The subprocess.call(command) method takes command as input and executes it. It returns 0 if the command executes successfully.

The command to ping a server will be ping -c 1 host_address for Unix and ping -n 1 host_address for Windows, where 1 is the number of packets and host_address is the server address we want to ping.

We can use the platform.system() method first to check the OS of the machine and then run the command accordingly. The below example code demonstrates how to use the subprocess.call() method to execute the command to ping a server in Python.

import platform
import subprocess

def myping(host):
    parameter = '-n' if platform.system().lower()=='windows' else '-c'

    command = ['ping', parameter, '1', host]
    response = subprocess.call(command)

    if response == 0:
        return True
    else:
        return False
        
print(myping("www.google.com"))

Ping Server in Python Using the os.system() Method

The os.system(command) method takes the command (a string) as input and executes it in a subshell. The method returns 0 if the command executes without any error.

We can use the os.system() method in the following way to execute the ping server command:

import os

def myping(host):
    response = os.system("ping -c 1 " + host)
    
    if response == 0:
        return True
    else:
        return False
        
print(myping("www.google.com"))

Ping Server in Python Using the ping3.ping() Function

The ping(addr) function of the ping3 module takes server address as input and returns the ping time as output if the server is available and returns False if it is not available.

We can install the ping3 module with the root privileges.

pip install ping3

We can pass the server address to the ping() method to ping the server.

from ping3 import ping

def myping(host):
    resp = ping(host)

    if resp == False:
        return False
    else:
        return True
        
print(myping("www.google.com"))
Contribute
DelftStack is a collective effort contributed by software geeks like you. If you like the article and would like to contribute to DelftStack by writing paid articles, you can check the write for us page.