python - getting the MAC address properly in Windows

oridamari picture oridamari · Mar 8, 2015 · Viewed 19.1k times · Source

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?

Answer

lqhcpsgbl picture lqhcpsgbl · Jun 30, 2015

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())