portable Python ifconfig

Bart Van Loon bbbart at inGen.be
Sun Mar 4 01:36:01 EST 2007


It was 3 Mar 2007 18:43:57 -0800, when MonkeeSage wrote:
> Bart,
>
> Can you try this and let us know if it works for FreeBSD?

thanks for you suggestions!

> 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

apparenlty, it doesn't. :-(

I changes the except block into

    except Exception, e:
        print e

and added

if __name__ == '__main__':
     print ifconfig('ng0')
     print ifconfig('vr0')
     print ifconfig('vr2')
     print ifconfig('xl0')

ng0 exists and has an IP (virtual interface created by mpd)
vr0 exists but does not have an IP (phisical interface for mpd)
vr2 exists and has an IP configured
xl0 does not exist

output:

[Errno 25] Inappropriate ioctl for device
{'ifname': 'ng0'}
[Errno 25] Inappropriate ioctl for device
{'ifname': 'vr0'}
[Errno 25] Inappropriate ioctl for device
{'ifname': 'vr2'}
[Errno 25] Inappropriate ioctl for device
{'ifname': 'xl0'}

however, in Linux I get the following results:

[Errno 99] Cannot assign requested address
{'ifname': 'eth0'}
{'hwaddr': '0:17:f2:4c:a5:c', 'ifname': 'ath0', 'netmask': '255.255.255.0', 'addr': '192.168.50.104', 'brdaddr': '192.168.50.255'}
{'hwaddr': '0:0:0:0:0:0', 'ifname': 'tun0', 'netmask': '255.255.255.255', 'addr': '192.168.3.6', 'brdaddr': '0.0.0.0'}
[Errno 19] No such device
{'ifname': 'wielewoele'}

which seems 100% correct.

-- 
regards,
BBBart

   Susie: You'd get a good grade without doing any work.  
   Calvin: So?  
   Susie: It's wrong to get rewards you haven't earned.  
   Calvin: I've never heard of anyone who couldn't live with that.



More information about the Python-list mailing list