Python:获取默认网关的MAC地址 [英] Python: get MAC address of default gateway
问题描述
在Python中有没有快速获取默认网关的 MAC地址的方法?
Is there any quick way in Python to get the MAC address of the default gateway?
我无法从 Linux 计算机上执行任何 ARP请求我正在运行我的代码,所以它必须直接来自 ARP表。
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.
推荐答案
以下DevFS文件将提供此信息:
The following DevFS files will provide this information:
/proc/net/arp
/proc/net/route
找到0/0作为主机/掩码的路由条目:
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
并转换网关字段(它是小端十六进制...... grr):
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')
从那里,你可以在arp表中找到你的默认网关:
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
如果没有显示,请发出一次ping,然后再次检查,然后失败。
If it doesn't show up, issue a single ping, then check again, then fail.
这篇关于Python:获取默认网关的MAC地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!