Python:获取默认网关的MAC地址 [英] Python: get MAC address of default gateway

查看:1044
本文介绍了Python:获取默认网关的MAC地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆