1

如何使用 python 获得本地网卡的正确 MAC/以太网 ID?Google/stackoverflow 上的大部分文章都建议解析 ipconfig /all (windows) 和 ifconfig (Linux) 的结果。在 Windows (2x/xp/7) 上,“ipconfig /all”工作正常,但这是一种故障安全方法吗?我是 linux 新手,我不知道“ifconfig”是否是获取 MAC/以太网 ID 的标准方法。

我必须在基于本地 MAC/以太网 ID 的 python 应用程序中实现许可证检查方法。

当您安装了 VPN 或 VirtualBox 等虚拟化应用程序时,有一种特殊情况。在这种情况下,您将获得多个 MAC/以太网 ID。如果我必须使用解析方法,这不会成为问题,但我不确定。

干杯

普拉尚

4

3 回答 3

6
import sys
import os

def getMacAddress(): 
    if sys.platform == 'win32': 
        for line in os.popen("ipconfig /all"): 
            if line.lstrip().startswith('Physical Address'): 
                mac = line.split(':')[1].strip().replace('-',':') 
                break 
    else: 
        for line in os.popen("/sbin/ifconfig"): 
            if line.find('Ether') > -1: 
                mac = line.split()[4] 
                break 
    return mac      

是一个跨平台功能,将为您返回答案。

于 2010-11-23T17:20:11.420 回答
4

在 linux 上,可以通过 sysfs 访问硬件信息。

>>> ifname = 'eth0'
>>> print open('/sys/class/net/%s/address' % ifname).read()
78:e7:g1:84:b5:ed

这样,您就可以避免使用 ifconfig 和解析输出的复杂性。

于 2010-11-23T20:03:33.520 回答
2

我使用了基于套接字的解决方案,在 linux 上运行良好,我相信 windows 也可以

def getHwAddr(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s', ifname[:15]))
    return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]

getHwAddr("eth0")

原始来源

于 2010-11-23T18:12:31.043 回答