Portable (Linux/Mac/Win) way to get network interfaces names and their addresses?

Alessio Pace alessio.pace at gmail.com
Wed Jan 7 02:54:40 EST 2009


Hi,

I'm wondering how could I get, possibly in a pure Python solution, the
list of network addresses on a machine and the IP address of each of
them.

In fact I came across recently on two solutions, one that is pure
Python but that works only on Linux:

#############################
def all_interfaces():
    max_possible = 128  # arbitrary. raise if needed.
    bytes = max_possible * 32
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    names = array.array('B', '\0' * bytes)
    outbytes = struct.unpack('iL', fcntl.ioctl(
        s.fileno(),
        0x8912,  # SIOCGIFCONF
        struct.pack('iL', bytes, names.buffer_info()[0])
    ))[0]
    namestr = names.tostring()
    return [namestr[i:i+32].split('\0', 1)[0] for i in range(0,
outbytes, 32)]

def get_ip_address(ifname):
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    return socket.inet_ntoa(fcntl.ioctl(
        s.fileno(),
        0x8915,  # SIOCGIFADDR
        struct.pack('256s', ifname[:15])
    )[20:24])
###########################

and one other instead that is in the "netifaces" package (=>
http://alastairs-place.net/netifaces/) which is written in C.


Thanks in advance for any suggestion.
--
Alessio Pace.



More information about the Python-list mailing list