network.py
Go to the documentation of this file.
00001 #!/bin/env python
00002 
00003 import socket
00004 import struct
00005 import platform
00006 try:
00007     import fcntl
00008     NO_FCNTL = False
00009 except ImportError:
00010     NO_FCNTL = True
00011 import array
00012 
00013 SIOCGIFCONF = 0x8912
00014 SIOCGIFFLAGS = 0x8913
00015 
00016 IFF_MULTICAST = 0x1000   
00017 
00018 class IfConfigNotSupported(Exception): pass
00019 
00020 def ifconfig():
00021     """
00022     Fetch network stack configuration.
00023     """
00024     if NO_FCNTL:
00025         raise IfConfigNotSupported ( "No fcntl")
00026     
00027     class _interface:
00028         def __init__(self, name):
00029             self.name = name
00030             self.addresses = []
00031             self.up = False
00032             self.multicast = False
00033 
00034         def _first_ip(self):
00035             try:
00036                 return self.addresses[0]
00037             except IndexError:
00038                 return None
00039         ip = property(_first_ip)
00040 
00041     #An ugly hack to account for different ifreq sizes on
00042     #different architectures
00043     arch = platform.architecture()[0]
00044     if arch == "32bit": offsets = (32, 32)
00045     elif arch == "64bit": offsets = (16, 40)
00046     else: raise OSError ( "Unsupported architecture: %s" % (arch) )
00047         
00048     #Get the list of all network interfaces
00049     _socket = socket.socket (socket.AF_INET, socket.SOCK_DGRAM)
00050     buffer = array.array ( 'B', '\0' * 128 * offsets[1] )
00051     reply_length = struct.unpack ( 'iL', fcntl.ioctl(_socket.fileno(), SIOCGIFCONF, struct.pack ('iL', 4096, buffer.buffer_info()[0])))[0]
00052     if_list = buffer.tostring()    
00053     if_list = filter(lambda x: len(x[0]) > 0, [ (if_list[i:i+offsets[0]].split('\0', 1)[0], socket.inet_ntoa(if_list[i+20:i+24])) for i in range(0, 4096, offsets[1])])
00054     
00055     iff = {}
00056     
00057     #Get ip addresses for each interface
00058     for (ifname, addr) in if_list:
00059         iff[ifname] = iff.get (ifname, _interface(ifname) );
00060         flags, = struct.unpack ( 'H', fcntl.ioctl(_socket.fileno(), SIOCGIFFLAGS, ifname + '\0'*256)[16:18])
00061         iff[ifname].addresses.append ( addr )
00062         iff[ifname].up = bool(flags & 1)
00063         iff[ifname].multicast = bool(flags & IFF_MULTICAST)
00064         
00065     _socket.close()
00066     return iff
00067 
00068 


jackal_bringup
Author(s):
autogenerated on Thu Jul 4 2019 19:49:01