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 google.com") if (response == 0): pinstatus = "Reachable" else: pinstatus = "Not reachable" print(pinstatus) def checkpingstate(hostA): response2 = os.system("ping -c 1 " + hostA) if (response2 == 0): pinstatus2 = hostA + " is Reachable" else: pinstatus2 = hostA + " is Not reachable" return pinstatus2 response1=checkpingstate("www.ngelinux.com") print(response1)
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 google.com (216.58.196.78): 56 data bytes 64 bytes from 216.58.196.78: icmp_seq=0 ttl=51 time=491.183 ms 64 bytes from 216.58.196.78: icmp_seq=1 ttl=51 time=491.320 ms --- google.com 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 Reachable PING ngelinux.com (104.152.168.40): 56 data bytes --- ngelinux.com ping statistics --- 1 packets transmitted, 0 packets received, 100.0% packet loss www.ngelinux.com is Not reachable Process finished with exit code 0