Find local non-loopback ip address in Python
<p>How can I find a list of local non-loopback IP addresses in Python (and stay platform-independent)?</p>

<p>The <a href="https://pypi.python.org/pypi/netifaces" rel="nofollow">netifaces</a> package provides a platform-independent way of getting network interface and address info. The <a href="https://pypi.python.org/pypi/ipaddress" rel="nofollow">ipaddress</a> package (standard in Python3, external in Python2) provides a handy <code>is_loopback</code> method.</p>

<p>It's not exactly trivial, but here is some code that worked at least once for me:</p>

<pre><code>import netifaces
import ipaddress
from pprint import pprint


def get_local_non_loopback_ipv4_addresses():
    for interface in netifaces.interfaces():
        # Not all interfaces have an IPv4 address:
        if netifaces.AF_INET in netifaces.ifaddresses(interface):
            # Some interfaces have multiple IPv4 addresses:
            for address_info in netifaces.ifaddresses(interface)[netifaces.AF_INET]:
                address_object = ipaddress.IPv4Address(unicode(address_info['addr'], 'utf-8'))
                if not address_object.is_loopback:
                    yield address_info['addr']

pprint(list(get_local_non_loopback_ipv4_addresses()))
</code></pre>

<p>That <code>address_info</code> variable will also have <code>netmask</code> and <code>broadcast</code> keys you can access for more info.</p>

<p>The <code>IPv4Address</code> object also has <code>is_private</code> and <code>is_global</code> methods you can use for similar queries.</p>

python