Python中通过netifaces库获取本机网络接口的网关信息
发布时间:2024-01-13 18:30:43
使用 netifaces 库可以轻松获取本机网络接口的网关信息。下面是一个使用例子:
import netifaces as ni
# 获取当前连接的网络接口
def get_default_interface():
gateway_info = ni.gateways()
default_interface = gateway_info['default'][ni.AF_INET][1]
return default_interface
# 获取网关的IP地址
def get_gateway_ip(interface):
gateway_info = ni.gateways()
gateway_ip = gateway_info['default'][ni.AF_INET][0]
return gateway_ip
# 获取本机所有网络接口的网关信息
def get_all_gateways():
gateway_info = ni.gateways()
all_gateways = {}
for interface in gateway_info:
gateways = gateway_info[interface]
for gateway in gateways:
gw_ip = gateway[0]
gw_interface = gateway[1]
if gw_interface not in all_gateways:
all_gateways[gw_interface] = []
all_gateways[gw_interface].append(gw_ip)
return all_gateways
# 获取指定网络接口的MAC地址
def get_mac_address(interface):
mac_address = ni.ifaddresses(interface)[ni.AF_LINK][0]['addr']
return mac_address
# 主程序
def main():
default_interface = get_default_interface()
gateway_ip = get_gateway_ip(default_interface)
all_gateways = get_all_gateways()
mac_address = get_mac_address(default_interface)
print('主机名:', ni.gethostname())
print('当前连接的网络接口:', default_interface)
print('网关IP地址:', gateway_ip)
print('所有网络接口的网关信息:', all_gateways)
print('MAC地址:', mac_address)
if __name__ == '__main__':
main()
该例子中,首先通过 get_default_interface 函数获取当前连接的网络接口,然后调用 get_gateway_ip 函数获取该网络接口的网关IP地址。get_all_gateways 函数可以获取本机所有网络接口的网关信息。get_mac_address 函数可以获取指定网络接口的MAC地址。
最后,主程序调用以上函数并打印相关信息,例如主机名、当前连接的网络接口、网关IP地址、所有网络接口的网关信息以及MAC地址。
请注意,使用 netifaces 库需要在系统中安装该库。可以通过 pip install netifaces 命令来安装。
