在Python中查找本地非环回IP地址

时间:2016-10-11 23:56:51

标签: python

如何在Python中找到本地非环回IP地址列表(并保持与平台无关)?

1 个答案:

答案 0 :(得分:0)

netifaces包提供了一种独立于平台的获取网络接口和地址信息的方法。 ipaddress包(Python3中的标准,Python2中的外部)提供了方便的is_loopback方法。

这不是一件容易的事,但这里有一些代码至少对我有用过一次:

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

address_info变量还可以使用netmaskbroadcast个键来获取更多信息。

IPv4Address对象还有is_privateis_global种方法可用于类似查询。