Python网络:查找对应接口的MAC地址 [英] Python networking : find MAC address for corresponding interfaces
问题描述
我从 pmav99 找到了一个脚本.非常感谢他.
I has found a scripts from pmav99. Big thanks to him.
import socket
import psutil
def get_ip_addresses(family):
for interface, snics in psutil.net_if_addrs().items():
for snic in snics:
if snic.family == family:
yield (interface, snic.address, snic.netmask)
ipv4s = list(get_ip_addresses(socket.AF_INET))
print ipv4s
结果是:
[('Local Area Connection* 2', '169.254.189.147', '255.255.0.0'), ('Ethernet', '192.168.18.34', '255.255.255.0'), ('Wi-Fi', '192.168.1.102', '255.255.255.0'), ('Loopback Pseudo-Interface 1', '127.0.0.1', '255.0.0.0')]
但是在psutil的net_if_addrs()中,它还提供了每个接口的mac地址.那么如何将Mac地址添加到列表中呢? MAC地址的密钥名称也为地址.我找不到办法.
But in net_if_addrs() of psutil, it also provide mac-address of each interfaces. So how can i add the mac address to the list ? the keys name of MAC address also is address. I can't find the way to get it.
推荐答案
根据在文档中,MAC地址由家族psutil.AF_LINK
标注.该代码片段将获取接口名称以及MAC地址的列表.
According to the documentation, MAC addresses are noted by family psutil.AF_LINK
. This code fragment will get a list of interface names, along with the MAC addresses.
macs = list(get_ip_addresses(psutil.AF_LINK))
print macs
以下程序将产生从MAC地址到IPV4地址的映射:
The following program will produce a mapping from MAC addresses to IPV4 addresses:
import socket
import psutil
def get_ip_addresses(family):
for interface, snics in psutil.net_if_addrs().items():
for snic in snics:
if snic.family == family:
yield (interface, (snic.address, snic.netmask))
ipv4s = dict(get_ip_addresses(socket.AF_INET))
macs = dict(get_ip_addresses(psutil.AF_LINK))
mac2ipv4 = {macs[k][0]: ipv4s[k] for k in set(macs) & set(ipv4s)}
print mac2ipv4
这篇关于Python网络:查找对应接口的MAC地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!