Certainly! Below is a Python program that scans your local network to identify connected devices, displaying their IP addresses and hostnames. This program uses the scapy library for sending ARP (Address Resolution Protocol) requests, which is an efficient way to discover devices on a local network.
Prerequisites
-
Python 3.x: Ensure you have Python installed. You can download it from here.
-
Scapy Library: Install scapy using pip:
pip install scapy
-
Administrator/Superuser Privileges: Scanning the network using ARP requires elevated privileges. Run the script with administrative rights.
- Windows: Run your command prompt as Administrator.
- Linux/macOS: Use
sudo to execute the script.
Understanding the Approach
-
Determine the Local Network Range: The script identifies your machine's IP address and subnet mask to calculate the network range.
-
Craft and Send ARP Requests: For each IP in the network range, an ARP request is sent to check if a device is active at that IP.
-
Receive and Parse ARP Responses: Active devices respond to ARP requests with their MAC addresses, allowing the script to identify them.
-
Resolve Hostnames: Using socket.gethostbyaddr(), the script attempts to retrieve the hostname associated with each IP address.
-
Display Results: The script compiles and displays a list of active IP addresses along with their corresponding hostnames.
The Python Script
import scapy.all as scapy
import socket
from scapy.layers.l2 import ARP, Ether
import ipaddress
import sys
def get_local_ip():
"""Retrieve the local IP address of the machine."""
try:
# Connect to an external host to get the local IP address
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80)) # Google's DNS
local_ip = s.getsockname()[0]
s.close()
return local_ip
except Exception as e:
print(f"Error obtaining local IP: {e}")
sys.exit(1)
def get_network_range(ip):
"""Determine the network range based on the local IP."""
try:
# Assuming a subnet mask of 255.255.255.0
# Modify if your network uses a different subnet mask
network = ipaddress.IPv4Interface(f"{ip}/24").network
return str(network)
except Exception as e:
print(f"Error determining network range: {e}")
sys.exit(1)
def scan_network(network):
"""Scan the network using ARP requests to find active devices."""
print(f"Scanning network: {network}...")
arp_request = ARP(pdst=network)
broadcast = Ether(dst="ff:ff:ff:ff:ff:ff")
arp_request_broadcast = broadcast / arp_request
answered, unanswered = scapy.srp(arp_request_broadcast, timeout=2, verbose=False)
devices = []
for sent, received in answered:
devices.append({'ip': received.psrc, 'mac': received.hwsrc})
return devices
def get_hostname(ip):
"""Resolve the hostname for a given IP address."""
try:
hostname = socket.gethostbyaddr(ip)[0]
except socket.herror:
hostname = "Unknown"
return hostname
def display_devices(devices):
"""Display the list of active devices on the network."""
print("--------------------------------------------------")
print("IP Address\t\tHostname\t\tMAC Address")
print("--------------------------------------------------")
for device in devices:
hostname = get_hostname(device['ip'])
print(f"{device['ip']}\t\t{hostname}\t\t{device['mac']}")
print("--------------------------------------------------")
def main():
local_ip = get_local_ip()
network = get_network_range(local_ip)
devices = scan_network(network)
if devices:
display_devices(devices)
else:
print("No devices found on the network.")
if __name__ == "__main__":
main()
How the Script Works
-
Retrieve Local IP Address: The get_local_ip() function establishes a dummy connection to an external server (Google's DNS server) to determine the local machine's IP address.
-
Determine Network Range: The get_network_range() function calculates the network range assuming a /24 subnet mask (i.e., 255.255.255.0). If your network uses a different subnet mask, adjust the CIDR notation accordingly.
-
Scan the Network: The scan_network() function sends ARP requests to all IP addresses within the determined network range. Devices that respond are considered active.
-
Resolve Hostnames: For each active IP address, the get_hostname() function attempts to retrieve the hostname. If it fails (e.g., the device doesn't have a hostname set or reverse DNS is not configured), it marks the hostname as "Unknown."
-
Display Results: The display_devices() function neatly prints out the IP address, hostname, and MAC address of each active device.
Running the Script
-
Save the Script: Save the above script to a file, for example, network_scanner.py.
-
Run with Elevated Privileges:
Sample Output
Scanning network: 192.168.1.10/24...
--------------------------------------------------
IP Address Hostname MAC Address
--------------------------------------------------
192.168.1.1 router.local AA:BB:CC:DD:EE:FF
192.168.1.5 laptop.local 11:22:33:44:55:66
192.168.1.8 Unknown 77:88:99:AA:BB:CC
--------------------------------------------------
Notes and Tips
-
Subnet Mask: The script assumes a /24 subnet mask. If your network uses a different subnet (e.g., /16), modify the get_network_range function accordingly.
-
Performance: ARP scanning is generally fast on local networks. However, scanning larger subnets (like /16) may take longer.
-
Firewall and Security Settings: Some devices may not respond to ARP requests if they have firewalls or security settings that block such probes.
-
Hostname Resolution: Not all devices have hostnames configured or have reverse DNS entries, leading to "Unknown" hostnames.
-
Error Handling: The script includes basic error handling. For production-grade applications, consider enhancing exception handling and possibly adding logging mechanisms.
-
Cross-Platform Compatibility: While scapy works on Windows, Linux, and macOS, certain functionalities might behave differently across operating systems. Ensure scapy is correctly installed and functional on your platform.
Alternative Approaches
If you prefer not to use scapy, you can perform a simple ping sweep and attempt to resolve hostnames using Python’s built-in libraries. However, this approach may be slower and less efficient compared to ARP scanning. Here's a brief outline of how you might do it:
-
Ping Each IP Address: Use the subprocess module to send ICMP echo requests.
-
Check for Live Hosts: Determine which IPs respond to pings.
-
Resolve Hostnames: Use socket.gethostbyaddr() for each responsive IP.
Note: This method may require elevated privileges and can be slower, especially on larger networks.
Conclusion
The provided Python script offers a straightforward way to scan your local network for active devices, displaying their IP addresses and hostnames. By leveraging the scapy library, it efficiently sends ARP requests and processes responses to identify devices. Ensure you have the necessary permissions and dependencies installed before running the script.