Home » Tutorials » How to create a Network Scanner in Python

How to create a Network Scanner in Python

Have you ever wondered if there are others connected to your network?

Well in today’s article, we’re going to address that issue by making a network scanner using Nmap in Python, and all you need to do is enter your IP address. So let’s get started!

Table of Contents

Disclaimer

Please note: Before we proceed with this code, I must warn you not to use this code illegally or without consent since it is for educational purposes only.

RELATED: How to Build a WiFi Scanner in Python

How to Install Nmap

Let’s get everything set up before we jump in. There’s a small but crucial step: installing Nmap. It’s the key to unlocking everything we’re about to explore. Here’s what to do:

  • First, go to this website https://nmap.org/download.html 
  • Second, go to the corresponding system of your device for me it is Windows.
  • Third download Nmap, then install it, the process is easy and self-explanatory but be sure to remember the directory where Nmap will be installed.
  • Fourth, make sure to use an absolute path, what I mean is go to the directory where Nmap is installed and copy its path.

Once you do that, in your menu: Search for “Edit the system variables“. Click on it, then click on “Environment Variables“, after that, you’ll find two lists (user variables and system variables).

  • Go to the system variables select “Path” and click “Edit“.
  • Now, click “New“, paste the directory Nmap that you have copied, and click “OK“.

Congratulations, now you can install Nmap via the terminal or your command prompt.

Necessary Libraries

Make sure to install the tkinter and Nmap libraries for the code to function properly:

$ pip install tk
$ pip install python-nmap 

Once you run these commands exit your Python editor and enter again so you can use nmap.

Imports

Let us begin by importing the necessary Libraries:

  • First, we import tkinter, this will allow us to create a graphical user interface (GUI).
  • Second, we import the messagebox module that will allow us to use message boxes.
  • Third, we import nmap which will be used for Network Scanning.
import tkinter as tk
from tkinter import messagebox
import nmap

Defining the NetworkScannerGUI Class

The code below is the blueprint that will handle the main window and the network scanner.

class NetworkScannerGUI:
   def __init__(self, root):
       self.root = root

Setting Up the Main Window

Here, we set the title together with the geometry of the main window.

self.root.title("Network Scanner - The Pycodes")
self.root.geometry("600x400")

Creating GUI Elements

After setting up the Main Window, now we create elements to make it easy for the user to interact with the main window.

  • First, we create a label that will ask the user to put the IP address of the router, underneath it we create an entry field so the user can input the said IP address.
  • Then we create a button that will trigger the scan_network function.
  • Lastly, we make a label where the result will be displayed and we place it in a specific position while the other elements will be packed automatically in positions.
self.ip_label = tk.Label(root, text="Enter Router IP:")
self.ip_label.pack()


self.ip_entry = tk.Entry(root, width=30, font="arial, 13")
self.ip_entry.pack()


self.scan_button = tk.Button(root, text="Scan Network", command=self.scan_network)
self.scan_button.pack()


self.result_label = tk.Label(root, text="", font="arial, 12")
self.result_label.place(x=30,y=100)

Defining the scan_network Function

This function is triggered when the “Scan Network” button is clicked, once that happens this function will:

Check IP Address

This part of the code verifies if the user did input the IP address of the router or not. If he did not, then an error message will pop up asking the user to enter the IP address of the router.

def scan_network(self):
   ip_address = self.ip_entry.get()
   if not ip_address:
       messagebox.showerror("Error", "Please enter the router's IP address.")
       return

Extract IP address

Once the user enters the IP address, it will be retrieved by this part of the code, then it will be prepared for scanning.

ip_range = ip_address + '/24'

Perform Network Scan

Now we use nmap to scan the network hosts inside the range of the inputted IP address by the user.

try:
   nm = nmap.PortScanner()
   nm.scan(hosts=ip_range, arguments='-sn')

Process Scan Results

The below code will go through each scanned host to get the status and the device name if possible, then ready the result for display and update the result result_label.

result_text = ""
for host in nm.all_hosts():
   status = nm[host]['status']['state']
   hostnames = nm[host]['hostnames']
   device_names = ', '.join(hostname['name'] for hostname in hostnames) if hostnames else 'Unknown'
   result_text += f"Host: {host}\tStatus: {status}\tDevice Name: {device_names}\n"

Displaying Results

If the scanning process goes smoothly, then the results of the hosts connected to the network will be displayed on the updated result_label. However, if an error occurs during the scanning process then, an error message pops up.

   self.result_label.config(text=result_text)
except nmap.PortScannerError as e:
   messagebox.showerror("Error", f"An error occurred while scanning: {e}")

Main Block

This block is the one responsible for creating the Main Window and keeping it running and responsive to the user.

if __name__ == "__main__":
   root = tk.Tk()
   app = NetworkScannerGUI(root)
   root.mainloop()

Example

Full Code

import tkinter as tk
from tkinter import messagebox
import nmap


class NetworkScannerGUI:
   def __init__(self, root):
       self.root = root
       self.root.title("Network Scanner - The Pycodes")
       self.root.geometry("600x400")


       self.ip_label = tk.Label(root, text="Enter Router IP:")
       self.ip_label.pack()


       self.ip_entry = tk.Entry(root, width=30, font="arial, 13")
       self.ip_entry.pack()


       self.scan_button = tk.Button(root, text="Scan Network", command=self.scan_network)
       self.scan_button.pack()


       self.result_label = tk.Label(root, text="", font="arial, 12")
       self.result_label.place(x=30,y=100)


   def scan_network(self):
       ip_address = self.ip_entry.get()
       if not ip_address:
           messagebox.showerror("Error", "Please enter the router's IP address.")
           return


       ip_range = ip_address + '/24'


       try:
           nm = nmap.PortScanner()
           nm.scan(hosts=ip_range, arguments='-sn')
           result_text = ""
           for host in nm.all_hosts():
               status = nm[host]['status']['state']
               hostnames = nm[host]['hostnames']
               device_names = ', '.join(hostname['name'] for hostname in hostnames) if hostnames else 'Unknown'
               result_text += f"Host: {host}\tStatus: {status}\tDevice Name: {device_names}\n"
           self.result_label.config(text=result_text)
       except nmap.PortScannerError as e:
           messagebox.showerror("Error", f"An error occurred while scanning: {e}")


if __name__ == "__main__":
   root = tk.Tk()
   app = NetworkScannerGUI(root)
   root.mainloop()

Happy Coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top