How to get the local mac address?

Frank Millman frank at chagford.com
Thu Dec 15 02:08:26 EST 2005


bonono at gmail.com wrote:
> Sorry that I can't help you in any way but have a question myself.  Is
> there an OS independent way to get this thing(regardless of how to
> format it) in Python ? I know this may not matter if all you want is
> Windows but there is just another thread talking about one should write
> programs that is OS independent.
>
> Is this a problem of the network library of python ?

This is not a generic solution, but it works for me on Linux and
Windows

def getMacAddress():
    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:
        for line in os.popen("/sbin/ifconfig"):
            if line.find('Ether') > -1:
                mac = line.split()[4]
                break
    return mac

HTH

Frank Millman




More information about the Python-list mailing list