Create a Python Network Scanner: Find IPs & MACs

Network Scanner in Python

Introduction

Ever noticed your Wi-Fi slowing down mysteriously? Thinking if unauthorized devices are lurking on your network? Knowing how to scan for active devices can be a game-changer, whether youā€™re managing a home Wi-Fi or a complex office network.

In this tutorial, we will build a Python program that identifies all the devices connected to your network (Network Scanner). Donā€™t worry, no prior coding experience is needed! Weā€™ll guide you step-by-step, making it perfect for anyone curious about whatā€™s happening behind the scenes.

Remember, this is for educational purposes only. Letā€™s dive in and explore the power of Python for network discovery!

Important Note

This script is intended for educational purposes only. Always ensure you have proper authorization before scanning any network. Unauthorized network scanning can be illegal and unethical.

Set Up Your Environment

Before we begin, ensure you have Python 3 and the ā€˜scapyā€˜ (Documentation) library installed. Follow the instructions for your operating system.

For Linux and macOS Users:

Open your terminal and install ā€˜scapyā€™ using the following command:

sudo python3 -m pip install scapy

For Windows Users

  1. Open Command Prompt as Administrator:
    • Press ā€˜Win + Xā€˜ and select ā€œCommand Prompt (Admin)ā€ or ā€œWindows PowerShell (Admin)ā€.
  2. Install ā€˜scapyā€˜ using the following command:
python -m pip install scapy

Now youā€™re ready to start coding.

Start Creating Your Network Scanner

First, create a Python script to send ARP requests and gather responses from devices on the network. Hereā€™s the code:

import scapy.all as scapy

def scan(ip_range):
    print(f"Scanning IP range: {ip_range}")
    
    arp_request = scapy.ARP(pdst=ip_range)
    broadcast = scapy.Ether(dst="ff:ff:ff:ff:ff:ff")
    arp_request_broadcast = broadcast / arp_request
    
    print("Sending ARP requests...")
    answered_list = scapy.srp(arp_request_broadcast, timeout=5, verbose=True)[0]
    
    if not answered_list:
        print("No responses received.")
    else:
        print("Responses received.")
    
    devices = []
    for element in answered_list:
        device = {'ip': element[1].psrc, 'mac': element[1].hwsrc}
        devices.append(device)
        print(f"Device found: IP = {device['ip']}, MAC = {device['mac']}")
    
    return devices

In the above code:

  1. The ā€˜scanā€˜ function takes an IP range as input, sends ARP requests, and collects responses.
    • ā€œarp_request = scapy.ARP(pdst=ip_range)ā€œ: The ā€˜pdstā€˜ parameter is set to the IP range provided. ARP (Address Resolution Protocol) is used to map IP addresses to MAC addresses.
  2. The request is broadcasted to the entire network.
    • ā€œbroadcast = scapy.Ether(dst=ā€ff:ff:ff:ff:ff:ffā€)ā€œ: This creates an Ethernet frame with the destination MAC address set to the broadcast address (ff:ff:ff:ff:ff:ff), which means it will be sent to all devices on the local network.
  3. ā€œarp_request_broadcast = broadcast / arp_requestā€œ: This combines the Ethernet frame and the ARP request packet into a single packet to be sent out.
  4. ā€œanswered_list = scapy.srp(arp_request_broadcast, timeout=5, verbose=True)[0]ā€œ: This sends the packet and waits for responses.
    • ā€˜scapy.srp()ā€˜ is used to send and receive packets at the data link layer.
    • ā€˜arp_request_broadcastā€˜ is the packet being sent.
    • ā€˜timeout=5ā€˜ sets a timeout of 5 seconds to wait for responses.
    • ā€˜verbose=Trueā€˜ enables detailed output.
    • ā€˜[0]ā€˜ retrieves only the answered packets.

Now, we need to display the results in a readable format. Add this function to your script:

def display_devices(devices):
    if devices:
        print("\nIP\t\t\tMAC Address")
        print("-----------------------------------------")
        for device in devices:
            print(f"{device['ip']}\t\t{device['mac']}")
    else:
        print("No devices found.")

The above function prints the list of discovered devices in a tabular format.

Finally, we need to tie everything together and initiate the scan. Hereā€™s the main function:

def scan_network(ip_range):
    devices = scan(ip_range)
    display_devices(devices)

if __name__ == "__main__":
    ip_range = '192.168.1.0/24'
    scan_network(ip_range)

Please adjust the IP range according to your network.

How to Run the Script?

Save your script as ā€˜network_scan.pyā€™ and run it with privileges.

For Linux and macOS Users

  • Open your terminal.
  • Navigate to the directory where ā€˜network_scan.pyā€™ is saved.
  • Run the script using the following command:
sudo python3 network_scan.py

For Windows Users

  • Open Command Prompt as Administrator.
  • Navigate to the directory where ā€˜network_scan.pyā€™ is saved.
  • Run the script using:
python network_scan.py

Output

Scanning IP range: 192.168.18.0/24
Sending ARP requestsā€¦
Begin emission:
Finished sending 256 packets.

Received 23 packets, got 2 answers, remaining 254 packets
Responses received.
Device found: IP = 192.168.18.1, MAC = d9:cd:a9:f2:a5:89
Device found: IP = 192.168.18.186, MAC = 36:10:07:5d:36:d4

IP MAC Address
ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€”ā€“
192.168.18.1 d9:cd:a9:f2:a5:89
192.168.18.186 36:10:07:5d:36:d4

Recommended: Create a Keylogger Program using Python

Summary

In this tutorial, we built a powerful network scanner using Python. With just a few lines of code, you can now identify all active devices connected to your network.

We used Pythonā€™s ā€˜scapyā€˜ library to build this tool. If you are a network administrator, cybersecurity enthusiast, or just curious about your networkā€™s activity, this tool is gonna help you a lot.

For any query related to this article feel free to reach out to me at contact@pyseek.com.

Happy scanning!

Share your love
Subhankar Rakshit
Subhankar Rakshit

Hey there! Iā€™m Subhankar Rakshit, the brains behind PySeek. Iā€™m a Post Graduate in Computer Science. PySeek is where I channel my love for Python programming and share it with the world through engaging and informative blogs.

Articles:Ā 194