portable Python ifconfig

MonkeeSage MonkeeSage at gmail.com
Sun Mar 4 03:43:57 CET 2007


Bart,

Can you try this and let us know if it works for FreeBSD?

import socket, fcntl, struct

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}
    sock  = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    try:
        ifreq['addr']    = _ifinfo(sock, 0x8915, ifname) # SIOCGIFADDR
        ifreq['brdaddr'] = _ifinfo(sock, 0x8919, ifname) #
SIOCGIFBRDADDR
        ifreq['netmask'] = _ifinfo(sock, 0x891b, ifname) #
SIOCGIFNETMASK
        ifreq['hwaddr']  = _ifinfo(sock, 0x8927, ifname) #
SIOCSIFHWADDR
    except:
        pass
    sock.close()
    return ifreq

Regards,
Jordan




More information about the Python-list mailing list