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 p开发者_StackOverflow中文版ython 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
精彩评论