In Python, to find all IP addresses on the local network, we can use network libraries such as socket and scapy. Below, I'll walk through the steps to use these tools to discover active IP addresses on the local network.
Getting Local IP Address Using the socket Library
First, we can use the socket library to obtain the IP address of the local machine. This serves as the starting point for discovering other devices on the network.
pythonimport socket def get_local_ip(): s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) try: # doesn't have to be reachable s.connect(('10.254.254.254', 1)) IP = s.getsockname()[0] except Exception: IP = '127.0.0.1' finally: s.close() return IP
Scanning the Local Network Using the scapy Library
Next, we can use the scapy library to scan the entire subnet. scapy is a powerful Python library for network packet processing.
First, install scapy:
bashpip install scapy
Then, we can write a function to scan IP addresses on the network:
pythonfrom scapy.all import ARP, Ether, srp def scan_ip(local_ip): prefix = local_ip.rsplit('.', 1)[0] # Get IP address prefix # IP address range, e.g., 192.168.1.1/24 target_ip = f"{prefix}.1/24" # Create ARP request packet (who has) arp = ARP(pdst=target_ip) ether = Ether(dst="ff:ff:ff:ff:ff:ff") # Ethernet frame packet = ether/arp result = srp(packet, timeout=3, verbose=0)[0] # Send packet and receive response # Extract IP addresses from response packets live_hosts = [] for sent, received in result: live_hosts.append({'ip': received.psrc, 'mac': received.hwsrc}) return live_hosts # Main function if __name__ == "__main__": local_ip = get_local_ip() print(f"Your local IP address: {local_ip}") hosts = scan_ip(local_ip) print("Live hosts on the network:") for host in hosts: print(f"IP: {host['ip']}, MAC: {host['mac']}")
Explanation
- Getting Local IP: We first determine the IP address of the local machine, which is crucial for defining the IP range to scan.
- Defining IP Range: We generate all IP addresses within the same subnet by simply changing the last octet.
- Sending ARP Requests: We send ARP requests for each IP address to check which addresses respond.
- Collecting and Printing Results: For devices that respond to ARP requests, we record their IP and MAC addresses and print them out.
This method can effectively help you find all active devices on the same local area network.
2024年8月21日 01:34 回复