Search code examples
pythonlinuxipmac-addressarp

Python: get MAC address of default gateway


Is there any quick way in Python to get the MAC address of the default gateway?

I can't make any ARP requests from the Linux machine I'm running my code on, so it has to come directly from the ARP table.


Solution

  • The following DevFS files will provide this information:

    /proc/net/arp
    /proc/net/route
    

    Find the route entry with 0/0 as the host/mask:

    Iface   Destination     Gateway         Flags   RefCnt  Use     Metric  Mask            MTU     Window  IRTT                                                       
    eth0    00000000        B91A210A        0003    0       0       100     00000000        0       0       0                                                                             
    

    and convert the Gateway field (it's in little-endian hex... grr):

    import struct
    from IPy import IP
    address = IP(struct.unpack('<I', struct.pack('>I', int(i, 16)))[0])
    #Converts 'B91A210A' to IP('10.33.26.185')
    

    From there, you can find your default gateway in the arp table:

    IP address       HW type     Flags       HW address            Mask     Device
    10.33.26.185     0x1         0x2         e6:92:ec:f5:af:f7     *        eth0
    

    If it doesn't show up, issue a single ping, then check again, then fail.