Sure! Below is a Python script that scans a given network to find active devices and lists their IP addresses along with their hostnames. This script uses the standard library modules ipaddress, socket, and subprocess. It pings each IP in the subnet to check if it's active and then attempts to resolve the hostname.
Important: Before running this script, make sure you have permission to scan the network. Scanning networks without proper authorization may violate laws or network policies.
import ipaddress
import socket
import subprocess
from concurrent.futures import ThreadPoolExecutor
import platform
def ping(host):
"""
Ping a host on the network.
Args:
host (str): The IP address of the host to ping.
Returns:
bool: True if the host is reachable, False otherwise.
"""
# Determine the parameter for ping command based on the OS
param = '-n' if platform.system().lower() == 'windows' else '-c'
# Build the ping command
command = ['ping', param, '1', str(host)]
# Suppress the output
return subprocess.call(command, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT) == 0
def get_hostname(ip):
"""
Get the hostname for an IP address.
Args:
ip (str): The IP address.
Returns:
str: The hostname associated with the IP, or None if not found.
"""
try:
# Attempt to resolve the hostname
return socket.gethostbyaddr(ip)[0]
except socket.herror:
# Hostname could not be resolved
return None
def scan_network(network):
"""
Scan the network for active devices.
Args:
network (ipaddress.IPv4Network): The network to scan.
Returns:
list of tuples: A list containing tuples of (IP address, hostname).
"""
active_hosts = []
print(f"Scanning network {network}...\n")
with ThreadPoolExecutor(max_workers=100) as executor:
# Schedule ping operations for each host in the network
futures = {executor.submit(ping, host): host for host in network.hosts()}
for future in futures:
host = futures[future]
if future.result():
hostname = get_hostname(str(host))
active_hosts.append((str(host), hostname))
print(f"Found device: IP = {host}, Hostname = {hostname or 'Unknown'}")
return active_hosts
if __name__ == "__main__":
# Prompt the user to enter the network address in CIDR notation
network_address = input("Enter the network address in CIDR notation (e.g., 192.168.1.0/24): ").strip()
try:
# Create an IPv4 network object
network = ipaddress.IPv4Network(network_address, strict=False)
except ValueError as e:
print(f"Invalid network address: {e}")
exit(1)
# Scan the network
devices = scan_network(network)
# Display the results
print("\nActive devices on the network:")
for ip, hostname in devices:
print(f"IP Address: {ip}, Hostname: {hostname or 'Unknown'}")
How to Use This Script
-
Save the Script:
- Save the code above into a file named
network_scanner.py.
-
Run the Script:
-
Enter the Network Address:
-
View the Results:
- The script will scan the network and display active devices along with their IP addresses and hostnames.
Notes
Disclaimer
Please ensure that you have proper authorization to scan the network. Unauthorized network scanning can be illegal and unethical. Always respect privacy and comply with local laws and network policies.
Dependencies
This script uses only standard Python libraries and does not require any external packages.
Troubleshooting
Customization
Feel free to ask if you have any questions or need further assistance with this script!