From: Aaron Klingaman Date: Thu, 28 Jul 2005 22:57:20 +0000 (+0000) Subject: from X-Git-Tag: BOOTMANAGER_PL_BOX_STABLE~16 X-Git-Url: http://git.onelab.eu/?p=bootmanager.git;a=commitdiff_plain;h=874e2525a59815be6a39e12f580337f9c44ff6cb from http://forums.devshed.com/archive/t-51149/Ethernet-card-address-Through-Python-or-C add a function that will return the mac address for a given network device --- diff --git a/source/utils.py b/source/utils.py index b9a3746..5da5fcd 100644 --- a/source/utils.py +++ b/source/utils.py @@ -42,6 +42,10 @@ import os, sys, shutil import popen2 +import socket +import fcntl +import string +import exceptions from Exceptions import * @@ -158,3 +162,32 @@ def removefile( filepath ): return 1 + + +# from: http://forums.devshed.com/archive/t-51149/ +# Ethernet-card-address-Through-Python-or-C + +def hexy(n): + return "%02x" % (ord(n)) + +def get_mac_from_interface(ifname): + """ + given a device name, like eth0, return its mac_address. + return None if the device doesn't exist. + """ + + SIOCGIFHWADDR = 0x8927 # magic number + + s=socket.socket(socket.AF_INET,socket.SOCK_STREAM) + ifname = string.strip(ifname) + ifr = ifname + '\0'*(32-len(ifname)) + + try: + r= fcntl.ioctl(s.fileno(),SIOCGIFHWADDR,ifr) + addr = map(hexy,r[18:24]) + ret = (':'.join(map(str, addr))) + except IOError, e: + ret = None + + return ret +