Script to find IP of device using ARP traffic

Solving real-life problems one at a time. While configuring network devices, network engineers always face issue in finding the default IP address or the IP address already configured in the device. One method to find the IP address is to capture traffic using Wireshark and look for the source IP address in the ARP broadcast.

Python
import subprocess
from scapy.all import ARP, sniff
import psutil
import socket
import sys
import re
"""
Functions defined
"""
def enable_dhcp(interface_name): 
    
    command = f"netsh interface ipv4 set address name=\"{interface_name}\" source=dhcp"
    result = subprocess.run(command, stdout=subprocess.PIPE, shell=True)
    main_string = str(result.stdout.decode('utf-8').strip())
    pattern = r'\bRun as administrator\b'
    #sys.exit()
    if result.returncode==0:
        print (f"\nDHCP enabled on interface: {interface_name}")
    elif re.search(pattern, main_string):     
        
        print('\n'+result.stdout.decode('utf-8').strip())
        input("Please right-click the file and select \"Run as Administrator\"")
        sys.exit()
    else:
        print('\n'+result.stdout.decode('utf-8').strip())
        
    return result.returncode
    
def arp_display(pkt):
    if ARP in pkt and pkt[ARP].op == 1:  # If it's an ARP request (who-has)
        print(f"\nA device with \nIP\t\t: {pkt[ARP].psrc}\nMAC Address\t: {pkt[ARP].hwsrc}\nis sending ARP Request")
        
        
def display_ipv4_interfaces():
    # Get network interface addresses
    interface_addrs = psutil.net_if_addrs()
    ifaces_list = []
    print("=======================================")
    print("Network interfaces available in this PC")
    print("---------------------------------------")
    for interface, addrs in interface_addrs.items():
        for addr in addrs:
            if addr.family == socket.AF_INET:
                ifaces_list.append(interface)
    
    return ifaces_list
"""
Main Code
"""
if __name__ == "__main__":
    timeout = 30 # set timeout for sniffing if not packets received
    ifaces_list = display_ipv4_interfaces()
    for iface in ifaces_list:
        print (str(ifaces_list.index(iface)+1) + ' ' + iface)
    print("=======================================")    
    index = input("Select network interface: ")
    interface = ifaces_list[int(index)-1]
    stats = psutil.net_if_stats()[interface]
    
    enable_dhcp(interface)
    if stats.isup:
        try:
            print(f"\nSearching for Source IP in ARP broadcast in interface \"{interface}\" for {timeout} seconds")
            # sniffing network traffic for ARP packets
            sniff(filter="arp", prn=arp_display, store=0, iface=interface, count=5, timeout=timeout)
            input()
        except KeyboardInterrupt:
            sys.exit(0)
    else:
        print("\nSelected Network Interface is Down, Please check the connection.")
        input("\nPress any key to exit.")

This Python script is designed to perform the following tasks related to network interfaces, ARP (Address Resolution Protocol), and DHCP (Dynamic Host Configuration Protocol):

  1. Enable DHCP on a Selected Interface:
    • The function enable_dhcp(interface_name) enables DHCP on the specified network interface using the netsh command.
    • It checks the result of the command execution and prints messages accordingly. If DHCP is enabled successfully, it prints a success message. If the command requires administrator privileges, it prompts the user to run the script as an administrator. If there’s an error, it prints the error message.
  2. ARP Packet Display:
    • The function arp_display(pkt) is a callback function intended to be used with Scapy’s sniff function.
    • It checks if a captured packet is an ARP request (pkt[ARP].op == 1) and prints information about the device sending the ARP request, including the IP address and MAC address.
  3. Display IPv4 Interfaces:
    • The function display_ipv4_interfaces() retrieves a list of network interfaces with their IPv4 addresses using the psutil library.
  4. Main Code Execution:
    • The script starts by displaying available network interfaces and prompting the user to select one.
    • It then calls enable_dhcp() to enable DHCP on the selected interface.
    • It checks if the selected network interface is up (stats.isup). If the interface is up, it proceeds to sniff network traffic for ARP packets for a specified timeout using Scapy’s sniff function and the arp_display callback function.
    • If the interface is down, it prints a message indicating the issue.

Overall, the script focuses on network-related tasks, specifically DHCP configuration and ARP packet analysis. It provides a basic interface for users to select a network interface and view ARP requests on that interface. The script utilizes external libraries such as subprocess, scapy, psutil, and standard Python modules like socket and sys.

You may also like...

Leave a Reply

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