Advanced ARP Discovery Tool: Network Discovery with Python

Introduction

Network management and security play a critical role in the modern information technology landscape. As the complexity of computer networks increases, effectively monitoring and managing these networks becomes equally important. Various tools and techniques are employed to determine the status of devices on the network, identify security vulnerabilities, and optimize network performance. In this context, ARP (Address Resolution Protocol) stands out as an important protocol. ARP is used to convert IP addresses into physical MAC addresses, enabling communication between devices on the network. The ARP Discovery Tool can be particularly useful in these scenarios.

In this article, we will develop an advanced ARP discovery tool using the Python programming language by integrating the coloramaargparse, and scapy libraries. This tool will allow users to detect active devices within a specific network range and present the results in a colorful format to enhance user experience.

Learning Objectives

By following this article, you will acquire the following skills:

  • Command-Line Arguments in Python: Using the argparse library to receive user input from the command line.
  • Creating and Sending Network Packets: Creating and sending ARP packets using the scapy library.
  • Coloring Terminal Output: Using the colorama library to make terminal output more readable.
  • Developing an Advanced ARP Discovery Tool: Creating a user-friendly ARP discovery tool and enhancing its functionality.
Amazon Product
Mastering Scapy: A Comprehensive Guide to Network Analysis

Mastering Scapy: A Comprehensive Guide to Network Analysis

Mastering Network Analysis with Scapy” is not just about learning a tool; it’s about unlocking a deeper understanding of the digital world that surrounds us

-5% $20 on buymeacoffee

What is ARP (Address Resolution Protocol) ?

ARP (Address Resolution Protocol) is a network protocol used to map an Internet Protocol (IP) address to a physical machine address that is recognized in the local network. In simpler terms, ARP translates IP addresses into MAC (Media Access Control) addresses, which are essential for devices to communicate on a local area network (LAN). This protocol plays a crucial role in ensuring that data packets reach their intended destinations within the network, facilitating seamless communication between devices.

Project Purpose

The ARP discovery tool we are developing will enable users to quickly and effectively identify devices within a specific network range. Users will be able to specify their network interfaces and target IP ranges for scanning. Additionally, results will be presented in a colorful format to provide a user-friendly experience. This tool will help network administrators and security professionals better understand devices on the network and identify potential security vulnerabilities.

Let’s Start Writing Our Code

Below, we will examine the complete code for our ARP discovery tool, breaking it down into parts for explanation. These explanations will help you understand what each component does and how it works.

1. Importing Required Libraries
import argparse
from scapy.all import ARP, Ether, srp
from colorama import Fore, Style, init
  • argparse: Used for processing command-line arguments. It allows us to take user input that alters the program’s behavior.
  • scapy: A powerful library for creating and sending network packets. We import classes like ARPEther, and srp:
    • ARP: Used to create ARP packets.
    • Ether: Used to create Ethernet frames.
    • srp: A function used to send Ethernet frames and capture responses.
  • colorama: Used to color terminal output. It enhances user experience by making outputs more readable. Fore is used to set text colors.
2. Initializing Colorama
# Initialize colorama
init(autoreset=True)
  • init(autoreset=True): Initializes the Colorama library and ensures that after each print statement, the default color is restored due to the autoreset parameter. This prevents text color mixing in the terminal.
3. The ARPDiscover Class
class ARPDiscover:
    def __init__(self, interface, timeout):
        self.interface = interface
        self.timeout = timeout
  • ARPDiscover Class: This class is designed to perform ARP discovery operations.
  • The __init__ method: Called when an instance of the class is created. It takes the user’s specified network interface and timeout value, storing them as class attributes.
4. Device Discovery Method
def discover(self, target_ip):
    # Create ARP packet
    arp = ARP(pdst=target_ip)
    # Create Ethernet frame
    ether = Ether(dst="ff:ff:ff:ff:ff:ff")
    # Combine ARP packet and Ethernet frame
    packet = ether / arp
    
    # Send packets and capture responses with specified timeout
    result = srp(packet, timeout=self.timeout, iface=self.interface, verbose=False)[0]
    
    devices = []
    for sent, received in result:
        devices.append({'ip': received.psrc, 'mac': received.hwsrc})
    
    return devices
  • discover Method: Used to discover devices within a specified IP range.
    • ARP(pdst=target_ip): Creates an ARP packet targeting the specified IP range.
    • Ether(dst="ff:ff:ff:ff:ff:ff"): Creates an Ethernet frame that broadcasts to all devices on the network.
    • packet = ether / arp: Combines the ARP packet with the Ethernet frame.
    • srp(packet, timeout=self.timeout, iface=self.interface, verbose=False): Sends the created packet through the specified interface and collects responses within the defined timeout period.
    • After receiving responses, each device’s IP and MAC addresses are added to a list.
5. Main Function
def main():
    # Set up argument parsing
    parser = argparse.ArgumentParser(description='ARP Discovery Tool')
    parser.add_argument('-i', '--interface', required=True, help='Network interface to use (e.g., eth0)')
    parser.add_argument('-t', '--target', required=True, help='Target IP range (e.g., 192.168.1.0/24)')
    parser.add_argument('--timeout', type=int, default=3, help='Timeout for ARP requests in seconds (default: 3)')

    args = parser.parse_args()
    
    # Create an instance of ARPDiscover with the specified timeout
    scanner = ARPDiscover(args.interface, args.timeout)
    
    print(Fore.YELLOW + f"Scanning on interface: {args.interface} for IP range: {args.target}...")
    
    # Perform ARP discovery
    devices = scanner.discover(args.target)
    
    print(Fore.GREEN + "Devices Found:")
    for device in devices:
        print(Fore.CYAN + f"IP: {device['ip']}, MAC: {device['mac']}")
  • main Function:
    • argparse.ArgumentParser: Creates an object for setting up command-line arguments.
    • add_argument: Defines which arguments must be provided by the user:
      • -i or --interface: Specifies which network interface to use (required).
      • -t or --target: Specifies which IP range to scan (required).
      • --timeout: Sets a timeout for each ARP request (default value is 3 seconds).
    • args = parser.parse_args(): Retrieves and processes user input arguments.
    • scanner = ARPDiscover(args.interface, args.timeout): Creates a new instance of ARPDiscover with values obtained from user input.
    • The scanning process begins, displaying found devices’ IP and MAC addresses in colored format.
6. Running the Program
if __name__ == "__main__":
    main()
  • This section ensures that when the script is run directly, it calls the main function (main). If the script is imported into another file, this part will not execute.

Usage Example

To run this script from a terminal or command prompt, you can use a command like:

Here, eth0 specifies which network interface to use; 192.168.1.0/24 indicates which IP range will be scanned. The --timeout parameter allows you to set a maximum wait time for each ARP request.

Conclusion

In this article, we developed an advanced ARP discovery tool using Python. Users can easily detect active devices on their networks with this tool. By integrating the libraries argparsescapy, and colorama, we created a functional yet user-friendly application. The tool we developed is not just a simple scanner; it also provides valuable information for network administrators and security professionals. By identifying devices on the network more easily, potential security vulnerabilities can be detected more readily, allowing necessary precautions to be taken.

It is anticipated that as such tools continue to evolve in future developments, processes related to network management will become more effective. Thanks to Python’s flexibility, integration with different protocols can be achieved while new features can be added to enhance functionality further.

You May Be Interested In

15 thoughts on “Advanced ARP Discovery Tool: Network Discovery with Python”

  1. Can I write a function that filters discovered devices based on specific criteria (e.g., only showing devices with certain MAC address prefixes)?

    Reply
    • This function filters the discovered devices based on a specified MAC address prefix, allowing users to focus on specific types of devices in their network scans.

      
      def filter_devices(devices, mac_prefix):
          filtered = [device for device in devices if device['mac'].startswith(mac_prefix)]
          return filtered
      
      # Usage
      filtered_devices = filter_devices(devices, '0a:1b:22')
      print(Fore.GREEN + "Filtered Devices Found:")
      for device in filtered_devices:
          print(Fore.CYAN + f"IP: {device['ip']}, MAC: {device['mac']}")
      
      

      Let it be your work to integrate this into the class as homework 😀

      Reply
  2. The explanations for each section of code are comprehensive and easy to understand, making this a great resource for both beginners and experienced developers.

    Reply
    • Of course there is, for example you can record with json file management, or you can record to cvs file.
      I also shared a tool like this on github, of course it is more advanced than this, DenizHalil Although he shared it for educational purposes in the simplest way, it is an extremely comprehensive and beautiful tool (If I were you, I would copy the tool and publish it on github ahahah)

      Reply

Leave a Reply