The Raspberry Pi network scanner that we will be creating in the following tutorial will scan through your local network and get the local IP address and MAC address of all devices connected to your network. To achieve this we are going to use the scapy module in a python script.
We can use this tool to monitor the devices connected to our local network. This can help you keep your network safe.
Contents
Logic
Private IP addresses fall under 3 different ranges:
- 10.0.0.0 – 10.255.255.255
- 172.16.0.0 – 172.31.255.255
- 192.168.0.0 – 192.168.255.255
You will have to find the range of IP addresses that is being used in your network. Most often the range is from 192.168.0.0 – 192.168.0.255 (set by default). However, in my case the range is from 192.168.1.0-192.168.1.255
In our code we will be looping through all addresses that belong to this range. For every iteration we will ping the IP address and obtain its MAC address as well. This pair of IP addresses and MAC addresses is what we will print.
Code
Lets create a python file called wifi_scan.py
You can also clone the code from this GitHub repository.
https://github.com/sashreek1/wifi_recon_tool
import scapy.all as scapy
def scan(ip):
arp_request = scapy.ARP(pdst=ip)
broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast/arp_request
answered_list = scapy.srp(arp_request_broadcast, timeout=0.25,verbose=False)[0]
clients_list = []
for element in answered_list:
client_dict = {"ip": element[1].psrc, "mac": element[1].hwsrc}
clients_list.append(client_dict)
return clients_list
print("IP"+"\t\t\t"+"MAC")
for i in range(0,256):
curr_ip = "192.168.1."+str(i)
scan_result = scan(curr_ip)
if scan_result != []:
print(scan_result[0]['ip']+"\t\t"+scan_result[0]['mac'])
To run this code write the following in the terminal
sudo python3 wifi_scan.py
Do not forget to use sudo as this script requires root permissions to run.
Explanation
- In line 1 we import the required packages i.e scapy
- In lines 3-13 we define the function called scan()
- From lines 4-7 we initialize the scan and create “answered_list” which stores the the result of scapy.srp()
- In lines 9-13 we store the mac address and IP addresses in the form of a dictionary, append them to “client_list” and return that list
- From lines 15-20 we run the main part of the program
- As explained in the logic section we loop from 0 to 255 and concatenate the value to create a valid IP address
- then we store the result of the scan in “scan_result” by calling the scan function on the IP address that we generated.
- In line 19 we check if the scan was successful and hence print the results in a readable manner.
Output
In the image above we can see the IP address of all devices connected to my local network along with their MAC addresses.
I hope you learnt how this simple network scanner program works and how it can be used. This is a great beginning for cybersecurity on IoT devices and services.
Happy learning 🙂