I need a cross platform method of determining the MAC address of a computer at run time. For windows the 'wmi' module can be used and the only method under Linux I could find was to run ifconfig and run a regex across its output. I don't like using a package that only works on one OS, and parsing the output of another program doesn't seem very elegant not to mention error prone.
Does anyone know a cross platform method (windows and linux) method to get the MAC address? If not, does anyone know any more elegant methods then those I listed above?
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.
pypi location
Good Intro to netifaces
One other thing that you should note is that
uuid.getnode()
can fake the MAC addr by returning a random 48-bit number which may not be what you are expecting. Also, there's no explicit indication that the MAC address has been faked, but you could detect it by callinggetnode()
twice and seeing if the result varies. If the same value is returned by both calls, you have the MAC address, otherwise you are getting a faked address.Note that you can build your own cross-platform library in python using conditional imports. e.g.
This will allow you to use os.system calls or platform-specific libraries.
For Linux let me introduce a shell script that will show the mac address and allows to change it (MAC sniffing).
Cut arguements may dffer (I am not an expert) try:
To change MAC we may do:
will change mac address to 00:80:48:BA:d1:30 (temporarily, will restore to actual one upon reboot).
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
The cross-platform getmac package will work for this, if you don't mind taking on a dependency. It works with Python 2.6+ and 3.2+. It will try many different methods until either getting a address or returning None.
Disclaimer: I am the author of the package.