Cross-platform network probe with structured output. Created for reusable and efficient network scanning.
#!/usr/bin/env python3
import subprocess
import ipaddress
import netifaces
import sys
from multiprocessing import Pool
def ping_sweep(ip):
"""Perform a single ping and print IP if host responds."""
result = subprocess.run(
["ping", "-c", "1", "-W", "1", str(ip)],
stdout=subprocess.DEVNULL,
stderr=subprocess.DEVNULL,
)
if result.returncode == 0:
print(ip)
def get_primary_ipv4_network():
"""Return (ip_address, IPv4Network) for the first non-loopback interface."""
for interface in netifaces.interfaces():
addresses = netifaces.ifaddresses(interface).get(netifaces.AF_INET)
if not addresses:
continue
for address in addresses:
addr = address.get("addr")
netmask = address.get("netmask")
if not addr or not netmask:
continue
if ipaddress.ip_address(addr).is_loopback:
continue
# Build network using address and netmask
network = ipaddress.IPv4Network(f"{addr}/{netmask}", strict=False)
return addr, network
return None, None
if __name__ == "__main__":
ip_address, network = get_primary_ipv4_network()
if not ip_address or not network:
print("Failed to retrieve IP address or network. Please check your network connection.")
sys.exit(1)
print("Host IP address:", ip_address)
print("Network prefix:", network.network_address)
print("CIDR network:", network)
# Build list of host IPs in this network (skips network and broadcast)
ip_addresses = [str(ip) for ip in network.hosts()]
# Create a pool of worker processes
pool = Pool()
# Perform ping sweep asynchronously
for ip in ip_addresses:
pool.apply_async(ping_sweep, (ip,))
# Close the pool to prevent further tasks from being submitted
pool.close()
# Wait for the worker processes to complete
pool.join()