# Ping Sweeper In Python

Following an article, I wrote sometime back about [pinging with Python](https://blog.octachart.com/ping-with-python), I promised that I would also write about a script that can do a ping sweeper and you don't have to be a network engineer to perform this.

If you missed that article, you can [read it](https://blog.octachart.com/ping-with-python), especially if you don't know what exactly pinging is. 

<center>

![ping-removebg-preview.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1650880142196/_xSAcjdS0.png)

</center>

In this article, we shall basically use the ```subprocess``` module;

The [subprocess module](https://docs.python.org/3/library/subprocess.html) allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes.

 It basically lets you start new applications right from the Python program you are currently writing. 

So let's start by importing it;
```
import subprocess

```
I am currently connected to public wifi and its default gateway is ``` 10.10.50.1 ```. So I will loop through the 254 maximum hosts we can have on that level.

Before we proceed further, let's create a variable to that default gateway and leave the last octet in the IP which is the host portion of the IP address.

```
network="10.10.50."
IPs = []
```
Also created a list that will hold all our IPs that will be live.

Let's create a main ```for loop``` that we shall use to append the host and ping that particular host to the default gateway.

```
for host in range(1,255):
    IP = network + str(host)
``` 
Under the same ```for loop```, let's spawn a new process using the ``` subprocess```  module. 
``` 
process = subprocess.run('ping -c 1 -w 1 '+ IP,stdout=subprocess.PIPE, shell=True)
``` 
The first command helps us ```ping``` with ```-c 1``` which is a routing compartment identifier. The ```-w 1``` is for a timeout in milliseconds.

The ```stdout=subprocess.PIPE``` will hide the output of the ```ping``` command

Setting the ```shell``` argument to a ```True``` value causes the subprocess to spawn an intermediate ```shell``` process, and tell it to run the command.

Now under the same indentation (```for loop```), let's get the IPs that are actually live when we ```ping``` with return codes.
```
if process.returncode == 0:
        IPs.append(IP)
        print(f" {IP} IS ALIVE !! ")
```
We also append that live IP to the IPs list variable that will help us get the total number of hosts available in that range.

Out of the ```for loop```, we could add an information output if we're done and get the number of hosts.

I am also using a tool called [```Fing```](https://www.fing.com/) which helps me get all the network hosts. 

```Fing``` is one of the top-ranking free network scanner apps for PC and Mobile. One of the best ways to run network and IP analysis, device recognition and security checks.

When I compared the results everything was perfect.

So our entire script looks like this;

```
import subprocess

network="10.10.50."
IPs = []

for host in range(1,255):
    IP = network + str(host)
    
    process = subprocess.run('ping -c 1 -w 1 '+ IP,stdout=subprocess.PIPE, shell=True)
  
    if process.returncode == 0:
        IPs.append(IP)
        print(f" {IP} IS ALIVE !! ")
        
print(f"Ping completed successfully & there are {len(IPs)} IPs hosts!")
``` 
Running the above script which will take some time;


Note: You will need admin privileges to be able to run that script successfully. Also doing this on a Private network may be dangerous and maybe you may want to test it on your own home network.


There is also an ```ipaddress``` module that can help us get all network hosts. <br>
Python's ```ipaddress``` module is an underappreciated gem from the Python standard library.

The ```ipaddress``` provides the capabilities to create, manipulate and operate on IPv4 and IPv6 addresses and networks. 


```
import ipaddress

mynet = ipaddress.ip_network('192.168.0.0/16') 
for host in mynet.hosts():                    
    host = str(host)
    print(host
``` 
The above will print all the hosts in that range and the last one would be ```192.168.255.254```

Find all the code in this article [here](https://github.com/Ronlin1/ping-with-python/blob/main/ping_sweeper.py) 🚀🚀 .

### 🌟 Conclusion
Once again, hope you learned something today from my little closet.

Please consider subscribing or following me for related content, especially about Tech, Python & General Programming.

You can show extra love by buying me a coffee to support this free content and I am also open to partnerships, technical writing roles, collaborations and Python-related training or roles.

<center>

<a href="https://www.buymeacoffee.com/RonnieAtuhaire" target="_blank"><img src="https://cdn.buymeacoffee.com/buttons/default-orange.png" alt="Buy Ronnie A Coffee" height="41" width="174"></a>

📢 You can also follow me on [Twitter](https://twitter.com/intent/follow?screen_name=AfroBoyUg) : ♥ ♥  Waiting for you! 🙂
</center>
