Python: get MAC address of default gateway

て烟熏妆下的殇ゞ 提交于 2019-12-11 02:32:38

问题


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.


回答1:


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.




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/15407354/python-get-mac-address-of-default-gateway

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!