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?
Try this with Python 2:
import uuid
def get_mac():
mac_num = hex(uuid.getnode()).replace('0x', '').upper()
mac = '-'.join(mac_num[i : i + 2] for i in range(0, 11, 2))
return mac
print get_mac()
If you're using Python 3, try this:
import uuid
def get_mac():
mac_num = hex(uuid.getnode()).replace('0x', '').upper()
mac = '-'.join(mac_num[i: i + 2] for i in range(0, 11, 2))
return mac
print (get_mac())
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.
Using Python 3 specs:
>>> import uuid
>>> mac_addr = hex(uuid.getnode()).replace('0x', '')
>>> print(mac_addr)
>>> 94de801e0e87
>>> ':'.join(mac_addr[i : i + 2] for i in range(0, 11, 2))
>>> '94:de:80:1e:0e:87
Or
print(':'.join(['{:02x}'.format((uuid.getnode() >> i) & 0xff) for i in range(0,8*6,8)][::-1]))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With