简体   繁体   中英

MAC, ethernet id using python

How do you get correct MAC/Ethernet id of local network card using python? Most of the article on Google/stackoverflow suggests to parse the result of ipconfig /all (windows) and ifconfig (Linux). On windows (2x/xp/7) 'ipconfig /all' works fine but is this a fail safe method? I am new to linux and I have no idea whether 'ifconfig' is the standard method to get MAC/Ethernet id.

I have to implement a license check method in a python application which is based on local MAC/Ethernet id.

There is a special case when you have a VPN or virtualization apps such as VirtualBox installed. In this case you'll get more then one MAC/Ethernet Ids. This is not going to be a problem if I have to use parsing method but I am not sure.

Cheers

Prashant

import sys
import os

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      

Is a cross platform function that will return the answer for you.

On linux, you can access hardware information through sysfs.

>>> ifname = 'eth0'
>>> print open('/sys/class/net/%s/address' % ifname).read()
78:e7:g1:84:b5:ed

This way you avoid the complications of shelling out to ifconfig, and parsing the output.

I have used a socket based solution, works well on linux and I believe windows would be fine too

def 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]])[:-1]

getHwAddr("eth0")

Original Source

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM