All Ipaddress of your system

Question

The program gets all the ipaddress assigned to all the interfaces in your machine.

Solution

#!/usr/bin/python
# $Id$

"""
**Purpose**: The program gets all the ipaddress assigned to all the interfaces
in your machine.

**Description**: Get all the interfaces using SIOCGIFCONF ioctl call and then
use SIOCGIFADDR to get its address.

man networking says that      SIOCGIFADDR     Get interface address for
protocol family.

"""

import socket
import fcntl
import struct
import array

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])

for each in all_interfaces():
    if each:
        print get_ip_address(each)
Run this
Comments by Disqus