如何获取局域网内所有IP地址及其关联MAC地址?
Solution to Scan All IP-MAC Pairs in a Subnet
Great call on switching to srp() and targeting the subnet—you're already on the right track! Here's how to adjust your code to scan every device in your network and collect their IP and MAC addresses:
Step-by-Step Breakdown
- Target the Entire Subnet: Instead of a single IP in
pdst, use CIDR notation (like198.13.13.0/24) to specify all IPs in your network segment. Adjust the CIDR suffix (e.g.,/16,/24) based on your actual subnet mask. - Use
srp()Instead ofsrp1():srp1()only returns the first response, whilesrp()returns all answered and unanswered requests—perfect for scanning multiple devices. - Loop Through Responses: Iterate over the
answeredlist to extract the IP (psrc) and MAC (hwsrc) from each responding device.
Full Working Code
from scapy.all import Ether, ARP, srp # Configure the subnet to scan (adjust to match your network) target_subnet = "198.13.13.0/24" # Create Ethernet frame (broadcast to all devices on the network) eth_frame = Ether(dst="ff:ff:ff:ff:ff:ff") # Create ARP request packet asking who has each IP in the subnet arp_request = ARP(pdst=target_subnet) # Combine frames and send the request # Timeout prevents waiting indefinitely for unresponsive devices answered, unanswered = srp(eth_frame / arp_request, timeout=2, verbose=0) # Print formatted results print("IP Address\t\tMAC Address") print("-----------------------------------------") for sent, received in answered: # Extract and display IP and MAC from the response print(f"{received.psrc}\t\t{received.hwsrc}")
Key Notes
- Subnet Adjustment: Double-check
target_subnetmatches your network's actual range. For example, if your router is at192.168.1.1, your subnet is likely192.168.1.0/24. - Timeout: The
timeout=2parameter tells Scapy to stop waiting for responses after 2 seconds—increase this if you have slower devices on your network. - Verbose Mode: Setting
verbose=0keeps output clean. Remove it if you want to see detailed request/response logs. - Permissions: On most systems, you’ll need to run this script with administrative privileges (e.g.,
sudoon Linux/macOS) to send raw network packets.
内容的提问来源于stack exchange,提问作者adi pslr
相关产品推荐
相关产品推荐

