How to Discover All MAC Addresses on a Network Programmatically


2 views

When managing large networks with hundreds of devices, manually checking each machine's MAC address via SSH becomes impractical. Network administrators often need to:

  • Track device inventory
  • Implement MAC filtering
  • Troubleshoot connectivity issues
  • Monitor unauthorized devices

The Address Resolution Protocol (ARP) cache stores MAC-to-IP mappings for recently communicated devices. On Linux/macOS:

arp -a

Windows equivalent:

arp -a

This shows MAC addresses for devices your machine has recently talked to, but won't show inactive devices.

For a complete network scan, Nmap is the Swiss Army knife:

nmap -sn 192.168.1.0/24

To extract MAC addresses:

nmap -sn 192.168.1.0/24 | grep -E 'MAC Address: [0-9A-Fa-f]{2}(:[0-9A-Fa-f]{2}){5}'

Here's a Python script using Scapy for MAC discovery:

from scapy.all import ARP, Ether, srp

def scan_network(ip_range):
    arp = ARP(pdst=ip_range)
    ether = Ether(dst="ff:ff:ff:ff:ff:ff")
    packet = ether/arp
    
    result = srp(packet, timeout=3, verbose=0)[0]
    
    devices = []
    for sent, received in result:
        devices.append({'ip': received.psrc, 'mac': received.hwsrc})
    
    return devices

print(scan_network("192.168.1.0/24"))

For networks with SNMP-enabled devices:

snmpwalk -v 2c -c public 192.168.1.1 .1.3.6.1.2.1.4.22.1.2
  • Scanning may trigger security alerts
  • Some devices may block ARP requests
  • VLAN segmentation requires per-VLAN scanning
  • Consider using parallel scanning for speed

Other useful utilities include:

  • Angry IP Scanner
  • Advanced IP Scanner
  • Netdiscover

When managing large networks with hundreds of devices, manually checking each machine's MAC address via SSH becomes impractical. Network administrators need automated solutions for inventory management, security audits, and troubleshooting.

The easiest approach leverages the Address Resolution Protocol (ARP) cache already maintained by your system:

# Linux/Unix/MacOS
arp -a

# Windows
arp -a | findstr "dynamic"

# Python alternative
import os
os.system('arp -a > arp_table.txt')

For more comprehensive discovery, Nmap provides powerful network enumeration:

sudo nmap -sn 192.168.1.0/24
sudo nmap -sP 192.168.1.0/24 --script=broadcast-dhcp-discover

Here's a complete Python script using scapy for MAC discovery:

from scapy.all import *

def scan_network(ip_range):
    ans, unans = arping(ip_range, verbose=0)
    for sent, received in ans:
        print(f"IP: {received.psrc} - MAC: {received.hwsrc}")

scan_network("192.168.1.1/24")

For large-scale environments consider:

  • SNMP walks using tools like snmpwalk
  • Network management systems (NMS) like LibreNMS
  • DHCP server logs examination

Remember that MAC address spoofing is possible. Always combine with other identification methods for critical systems. Network scanning should only be performed on networks you administer.