I'm using Windows 7 and Python 2.6. I would like to get the MAC address of my network interface.
I've tried using the wmi module:
def get_mac_address():
c = wmi.WMI ()
for interface in c.Win32_NetworkAdapterConfiguration (IPEnabled=1):
return interface.MACAddress
However, experienced issues when executed without internet connectivity.
I've tried using the uuid module:
from uuid import getnode
print getnode()
However, return value is a 48 byte representation of the MAC address
66610803803052
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?
解决方案
This works:
>>> address = 1234567890
>>> h = iter(hex(address)[2:].zfill(12))
>>> ":".join(i + next(h) for i in h)
'00:00:49:96:02:d2'
Or:
>>> "".join(c + ":" if i % 2 else c for i, c in enumerate(hex(address)[2:].zfill(12)))[:-1]
'00:00:49:96:02:d2'
Or:
>>> 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'
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.