Python-仅获取连接的本地NIC的MAC地址 [英] Python - Get MAC address of only the connected local NIC
本文介绍了Python-仅获取连接的本地NIC的MAC地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
目标是收集连接的本地NIC的MAC地址,
而不是所有本地NIC的列表 :)
The goal is to collect the MAC address of the connected local NIC, not a list of all local NICs :)
通过使用 socket
和 connect(to_a_website)
,
我可以只使用 getsockname()
获取用于连接到Internet的IP,
。
By using socket
and connect (to_a_website)
,
I can just use getsockname()
to get the IP,
that is being used to connect to the Internet.
但是如何从IP中获取本地NIC的MAC地址?
But from the IP how can I then get the MAC address of the local NIC ?
该问题的主要原因是是否有多个NIC。
Main reason for the question is if there are multiple NICs.
推荐答案
正如vartec建议的那样, netifaces
应该可以很好地用于IP-> iface:
As vartec suggested netifaces
should work well to go from IP->iface:
import netifaces as nif
def mac_for_ip(ip):
'Returns a list of MACs for interfaces that have given IP, returns None if not found'
for i in nif.interfaces():
addrs = nif.ifaddresses(i)
try:
if_mac = addrs[nif.AF_LINK][0]['addr']
if_ip = addrs[nif.AF_INET][0]['addr']
except IndexError, KeyError: #ignore ifaces that dont have MAC or IP
if_mac = if_ip = None
if if_ip == ip:
return if_mac
return None
测试:
>>> mac_for_ip('169.254.90.191')
'2c:41:38:0a:94:8b'
这篇关于Python-仅获取连接的本地NIC的MAC地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文