Introd

Hunting around on google revealed very little on accessing the hosts IP address using Python, especially when it comes to accessing multiple IPs.

Thankfully, the answer is simple

Using ifaddr

Downloading and installing ifaddr is super simple, which is nice compared to some other more complex libraries such as netiface that requires the C++ build tools.

After installing ifaddr it really is as simple as the following code to go grab all the IP addresses on the device itself:


    import ifaddr
    adapters = ifaddr.get_adapters()
    all_ips_list = list()
    for adapter in adapters:
        for ip in adapter.ips:
            from pprint import pprint
            pprint(vars(ip))
            if type(ip.ip) == tuple:
                continue
            else:
                all_ips_list.append({'IP Address':ip.ip,'Adapter Name':adapter.nice_name})

produces the following…


{'ip': '127.0.0.1',
 'network_prefix': 8,
 'nice_name': 'Loopback Pseudo-Interface 1'}


As we can see, by printing all the variables within the object, ifaddr presents a nice simple way of being able to grab the IP addresses of the host machine.

This is perfect for sending metrics back to base, or even as part of a recon operation when reporting back where your code is currently running within the network.