如何在Python中找到本地非环回IP地址列表(并保持与平台无关)?
答案 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
变量还可以使用netmask
和broadcast
个键来获取更多信息。
IPv4Address
对象还有is_private
和is_global
种方法可用于类似查询。