Ping Sweep in Python

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.

Ping Sweep

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.

  1. Destination machine is shutdown
  2. 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’ 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')
for line in result.readlines():


Pinging with 32 bytes of data:
Reply from bytes=32 time=214ms TTL=54
Reply from bytes=32 time=265ms TTL=54
Reply from bytes=32 time=272ms TTL=54
Reply from bytes=32 time=285ms TTL=54

Ping statistics for
    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










Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s