portable Python ifconfig
MonkeeSage
MonkeeSage at gmail.com
Sat Mar 3 20:17:59 EST 2007
On Mar 3, 3:38 pm, Bart Van Loon <bbb... at inGen.be> wrote:
> I'm looking for a portable (FreeBSD and Linux) way of getting typical
> ifconfig information into Python.
Here's a pure python version of the C extension, based on the recipes
you posted. In this version, the 'addr' key will not exist for a non-
existent / non-active interface.
import socket, fcntl, struct, platform
def _ifinfo(sock, addr, ifname):
iface = struct.pack('256s', ifname[:15])
info = fcntl.ioctl(sock.fileno(), addr, iface)
if addr == 0x8927:
hwaddr = []
for char in info[18:24]:
hwaddr.append(hex(ord(char))[2:])
return ':'.join(hwaddr)
else:
return socket.inet_ntoa(info[20:24])
def ifconfig(ifname):
ifreq = {'ifname': ifname}
infos = {}
osys = platform.system()
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
if osys == 'Linux':
# offsets defined in /usr/include/linux/sockios.h on linux 2.6
infos['addr'] = 0x8915 # SIOCGIFADDR
infos['brdaddr'] = 0x8919 # SIOCGIFBRDADDR
infos['hwaddr'] = 0x8927 # SIOCSIFHWADDR
infos['netmask'] = 0x891b # SIOCGIFNETMASK
elif 'BSD' in osys: # ???
infos['addr'] = 0x8915
infos['brdaddr'] = 0x8919
infos['hwaddr'] = 0x8927
infos['netmask'] = 0x891b
try:
for k,v in infos.items():
ifreq[k] = _ifinfo(sock, v, ifname)
except:
pass
sock.close()
return ifreq
ifc = ifconfig('ath0')
if ifc.has_key('addr'):
print ifc
I'm pretty sure the offsets would be different for BSD, but I don't
have any BSD boxes to test on (looks like from a bit of googling that
you might need to look at /compat/linux/linux_ioctl.h for the offsets
on BSDs). I'll leave it to you to fill in the BSD stuff.
Regards,
Jordan
More information about the Python-list
mailing list