In this blog, we will be creating basic ping sweep program using Python programming language.
Before we start writing ping sweep program, we need to discuss about ping or ICMP packets. Ping or ICMP consits of two packets ICMP Request and ICMP Reply.
In the below network, source sends ICMP Request packet and destination reply or acknowledge with ICMP reply packet.
Now there are some cases in which source does not get or receive ICMP reply packets from destination machine. We see Request Time Out or destination host unreachable on the CMD.
Below are the two conditions in which source does not receive ICMP reply packets.
- Destination machine is shutdown
- Ping or ICMP has been blocked by the firewall
Ping Sweep Program
We can use ping sweep program to find live host in the network by sending ICMP ECHO request and ICMP ECHO reply packets
Ping Sweep program make use of OS module and os.popen() function. In Windows operating system we use ping command from CMD to find live host. We have to provide ping command as the parameter to os.popen() function. We can pass DOS commands inside os.popen() function
Step1 Importing os module
Step 2 Using os.popen() function and passing ‘ping 188.8.131.52’ DOS command as a parameter to function. Assigning output of ping to result variable
Step 3 Printing each line of result variable using for loop
Below is the code
import os result = os.popen('ping 184.108.40.206') for line in result.readlines(): print(line)
Pinging 220.127.116.11 with 32 bytes of data: Reply from 18.104.22.168: bytes=32 time=214ms TTL=54 Reply from 22.214.171.124: bytes=32 time=265ms TTL=54 Reply from 126.96.36.199: bytes=32 time=272ms TTL=54 Reply from 188.8.131.52: bytes=32 time=285ms TTL=54 Ping statistics for 184.108.40.206: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 214ms, Maximum = 285ms, Average = 259ms Process finished with exit code 0