0
如何在Python中查找本地非回送IP地址列表(並保持與平臺無關)?在Python中查找本地非回送IP地址
如何在Python中查找本地非回送IP地址列表(並保持與平臺無關)?在Python中查找本地非回送IP地址
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
您可以用於類似查詢的方法。