7

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?

Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
oridamari
  • 561
  • 7
  • 12
  • 24

7 Answers7

7

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())
Gareth
  • 47
  • 1
  • 2
  • 7
lqhcpsgbl
  • 3,694
  • 3
  • 21
  • 30
  • 1
    You have to catch case when mac is short. You have to zfill() it. `mac_num = hex(uuid.getnode()).replace('0x', '').replace('L', '')` `mac_num = mac_num.zfill(12)` – zvi Feb 20 '17 at 08:42
4

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.

matsjoyce
  • 5,744
  • 6
  • 31
  • 38
2

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]))
usainzg
  • 965
  • 9
  • 13
1

Mac address from a given interface name:

https://gist.github.com/JayZar21/6f3fd031430d865d208c29ba55ce7ccb

# Python 2:

import socket
import fcntl
import struct

def get_hw_address(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]

# Python 3:

import fcntl
import socket
import struct
import binascii

def get_hw_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s',  bytes(ifname[:15], 'utf-8')))
    return ''.join(l + ':' * (n % 2 == 1) for n, l in enumerate(binascii.hexlify(info[18:24]).decode('utf-8')))[:-1]

Usage example:

get_hw_address("eth0")
J_Zar
  • 2,034
  • 2
  • 21
  • 34
  • Great solution, I modified slightly to have a similar return value as with "uuid.getnode()", i.e. `mac_str = ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1] return int(mac_str.translate(None, ":.- "), 16)` – Ñhosko Aug 03 '18 at 06:29
1

You cannot rely on the uuid module If you have multiple network interfaces. There's a 3rd party library that works cross-platform called getmac

Installation:

pip install getmac

Usage:

from getmac import get_mac_address
eth_mac = get_mac_address(interface="eth0")
win_mac = get_mac_address(interface="Ethernet 3")
ip_mac = get_mac_address(ip="192.168.0.1")
ip6_mac = get_mac_address(ip6="::1")
host_mac = get_mac_address(hostname="localhost")
updated_mac = get_mac_address(ip="10.0.0.1", network_request=True)
Jossef Harush Kadouri
  • 32,361
  • 10
  • 130
  • 129
0

code:

import re
from uuid import getnode


# to get physical address:
original_mac_address = getnode()
print("MAC Address: " + str(original_mac_address)) # this output is in raw format

#convert raw format into hex format
hex_mac_address = str(":".join(re.findall('..', '%012x' % original_mac_address)))
print("HEX MAC Address: " + hex_mac_address)

Output:

My Output:

MD. SHIFULLAH
  • 913
  • 10
  • 16
0

no third party, late to the party! python 3, windows only solution:

import subprocess, re

ipconfig_all = subprocess.check_output('ipconfig /all').decode()
mac_addr_pattern = re.compile(r'(?:[0-9a-fA-F]-?){12}')
mac_addr_list = re.findall(mac_addr_pattern, ipconfig_all)

print(mac_addr_list)
Sharan Arumugam
  • 353
  • 6
  • 12