#!/usr/bin/python3
import netifaces as ni
def get_network_info():
for interface in ni.interfaces():
try:
ip_addresses = ni.ifaddresses(interface)[ni.AF_INET]
for info in ip_addresses:
ip_address = info['addr']
print(f"Interface: {interface}, IP Address: {ip_address}")
mac_address = ni.ifaddresses(interface)[ni.AF_LINK][0]['addr']
print(f"Interface: {interface}, MAC Address: {mac_address}")
except KeyError:
# 如果接口没有IPv4或硬件地址,则会跳过
pass
get_network_info()
#!/usr/bin/python3
import netifaces
# 获取所有网络接口
interfaces = netifaces.interfaces()
for interface in interfaces:
addrs = netifaces.ifaddresses(interface)
if netifaces.AF_INET in addrs: # 检查IPv4地址
ip = addrs[netifaces.AF_INET][0]['addr']
print(f"{interface} IP地址: {ip}")
if netifaces.AF_LINK in addrs: # 检查MAC地址
mac = addrs[netifaces.AF_LINK][0]['addr']
print(f"{interface} MAC地址: {mac}")