Вопрос

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.

Это было полезно?

Решение

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.

Другие советы

Are you using Linux? You could parse the /proc/net/arp file. It contains the HW address of your gateway.

You can read from /proc/net/arp and parse the content, that will give you couples of known IP-MAC addresses.

The gateway is probably known at all times, if not you should ping it, and an ARP request will be automatically generated.

You can find the default gw in /proc/net/route

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top