1

How can I find a list of local non-loopback IP addresses in Python (and stay platform-independent)?

1 Answer 1

2

The netifaces package provides a platform-independent way of getting network interface and address info. The ipaddress package (standard in Python3, external in Python2) provides a handy is_loopback method.

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

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

That address_info variable will also have netmask and broadcast keys you can access for more info.

The IPv4Address object also has is_private and is_global methods you can use for similar queries.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.