How to check ping status of a domain/host name in python ?

Today in this post, we will understand how to check ping status of a domain in python programming language.

I. Program

import os
response=os.system("ping -c 2")

if (response == 0):
    pinstatus = "Reachable"
    pinstatus = "Not reachable"


def checkpingstate(hostA):
    response2 = os.system("ping -c 1 " + hostA)
    if (response2 == 0):
        pinstatus2 = hostA + " is Reachable"
        pinstatus2 = hostA + " is Not reachable"
    return pinstatus2


II. Explanation
a. In the above program, we have created a function called “checkpingstate” which takes the hostname to check ping status.
b. And returns the ping status.
c. The ping status which is returned is stored in “response” variable.
d. This variable value is printed in end.


III. Output

PING ( 56 data bytes
64 bytes from icmp_seq=0 ttl=51 time=491.183 ms
64 bytes from icmp_seq=1 ttl=51 time=491.320 ms

--- ping statistics ---
2 packets transmitted, 2 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 491.183/491.251/491.320/0.069 ms
PING ( 56 data bytes

--- ping statistics ---
1 packets transmitted, 0 packets received, 100.0% packet loss is Not reachable

Process finished with exit code 0

Note:- The point to note here is “os” library which is imported to run the OS level command inside python programming language.
0 0 votes
Article Rating
Notify of

Inline Feedbacks
View all comments