Getting MAC Address Getting MAC Address python python

Getting MAC Address


Python 2.5 includes an uuid implementation which (in at least one version) needs the mac address. You can import the mac finding function into your own code easily:

from uuid import getnode as get_macmac = get_mac()

The return value is the mac address as 48 bit integer.


The pure python solution for this problem under Linux to get the MAC for a specific local interface, originally posted as a comment by vishnubob and improved by on Ben Mackey in this activestate recipe

#!/usr/bin/pythonimport fcntl, socket, structdef getHwAddr(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]])print getHwAddr('eth0')

This is the Python 3 compatible code:

#!/usr/bin/env python3# -*- coding: utf-8 -*-import fcntlimport socketimport structdef getHwAddr(ifname):    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)    info = fcntl.ioctl(s.fileno(), 0x8927,  struct.pack('256s', bytes(ifname, 'utf-8')[:15]))    return ':'.join('%02x' % b for b in info[18:24])def main():    print(getHwAddr('enp0s8'))if __name__ == "__main__":    main()


netifaces is a good module to use for getting the mac address (and other addresses). It's crossplatform and makes a bit more sense than using socket or uuid.

>>> import netifaces>>> netifaces.interfaces()['lo', 'eth0', 'tun2']>>> netifaces.ifaddresses('eth0')[netifaces.AF_LINK][{'addr': '08:00:27:50:f2:51', 'broadcast': 'ff:ff:ff:ff:ff:ff'}]