How to get Mac address of ethernet port?

William Ray Wing wrw at mac.com
Mon Jan 13 10:42:25 EST 2014


On Jan 11, 2014, at 11:34 AM, Michael Torrie <torriem at gmail.com> wrote:

> On 01/11/2014 07:35 AM, Andriy Kornatskyy wrote:
>> Sam,
>> 
>> How about this?
>> 
>> from uuid import getnode as get_mac
>> '%012x' % get_mac()
> 
> This seems to work if you have only one ethernet adapter.  Most
> computers have two (wired and wireless) adapters.
> 
> Getting a mac address is platform-specific, and the OP has not specified
> what OS he is using.
> 
> On Windows I imagine you'd have to access the WMI subsystem in Windows.
> 
> On Linux you could access the /sys/devices/virtual/net/<interface name>
> file in the sysfs filesystem.  I'm sure there are other ways.
> 
> No idea on OS X.
> -- 
> https://mail.python.org/mailman/listinfo/python-list

There are probably several ways in OS-X, just as there are in any other UNIX system.  The one I've used is to spawn a subprocess and run the "ifconfig" command with no arguments (which doesn't require any special privileges).  This will return a string of all the network interfaces (including the loopback and firewire interfaces in addition to Ethernet and WiFi) and their config specs.  The OP would then parse this string looking for the location of the phrase "status: active" and then back up to the mac address that precedes it.  More work than using uuid, but this guarantees a current and correct answer.

>>> import string
>>> import subprocess
>>> mac_result = subprocess.Popen(['ifconfig'], stderr = subprocess.PIPE, stdout = subprocess.PIPE).communicate()[0]
>>> mac_loc = string.find(mac_result, "status: active")

...and so on.

Bill


More information about the Python-list mailing list