python-在Windows中正确获取MAC地址 [英] python - getting the MAC address properly in Windows
问题描述
我正在使用Windows 7和Python 2.6.我想获取我的网络接口的MAC地址.
I'm using Windows 7 and Python 2.6. I would like to get the MAC address of my network interface.
我尝试使用wmi
模块:
def get_mac_address():
c = wmi.WMI ()
for interface in c.Win32_NetworkAdapterConfiguration (IPEnabled=1):
return interface.MACAddress
但是,在没有Internet连接的情况下执行时会遇到问题.
However, experienced issues when executed without internet connectivity.
我尝试使用uuid
模块:
from uuid import getnode
print getnode()
但是,返回值是MAC地址的48字节表示形式
However, return value is a 48 byte representation of the MAC address
66610803803052
1)如何将给定的数字转换为ff:ff:ff:ff:ff:ff
格式?
2)有没有更好的方法来获取MAC地址?
1) How should I convert the given number to ff:ff:ff:ff:ff:ff
format?
2) Is there a better way to get the MAC address?
推荐答案
这有效:
>>> address = 1234567890
>>> h = iter(hex(address)[2:].zfill(12))
>>> ":".join(i + next(h) for i in h)
'00:00:49:96:02:d2'
或者:
>>> "".join(c + ":" if i % 2 else c for i, c in enumerate(hex(address)[2:].zfill(12)))[:-1]
'00:00:49:96:02:d2'
或者:
>>> h = hex(address)[2:].zfill(12)
>>> ":".join(i + j for i, j in zip(h[::2], h[1::2]))
'00:00:49:96:02:d2'
首先将数字转换为十六进制,将其填充为12个字符,然后将其转换为一系列的两个字符字符串,然后将其与冒号连接起来.但是,这取决于您的MAC查找方法的准确性.
You first convert the number to hex, pad it to 12 chars, and then convert it to a series of two char strings, and then join them with colons. However, this depends on the accuracy of your MAC-finding method.
这篇关于python-在Windows中正确获取MAC地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!