Getting Local MAC Address

Frank Millman frank at chagford.com
Sat Apr 3 02:25:26 EDT 2010


"Booter" <colo.avs96 at gmail.com> wrote in message 
news:ec6d247c-a6b0-4f33-a36b-1d33eace642f at k19g2000yqn.googlegroups.com...
> Hello all,
>
> I am new to python ans was wondering if there was a way to get the mac
> address from the local NIC?
>
> Thanks for your help.
>
> Gerad

This is what I use -

------------------------
def get_mac_address():
    if sys.platform == 'win32':
        for line in os.popen("ipconfig /all"):
            if line.lstrip().startswith('Physical Address'):
                mac = line.split(':')[1].strip().replace('-',':')
                break
    else:
#       mac = os.popen("/sbin/ifconfig|grep Ether|awk {'print 
$5'}").read()[:-1]
        for line in os.popen("/sbin/ifconfig"):
            if 'Ether' in line:
                mac = line.split()[4]
                break
    return mac

------------------------

I only target windows and linux. I don't know if it works for all platforms.

I wrote this a long time ago. I think it would now be preferable to use 
subprocess() instead of os.popen().

Note the commented-out line in the linux block. This is an alternative 
method I cribbed from somewhere. Not as readable, but probably faster.

HTH

Frank Millman





More information about the Python-list mailing list