Python,如何使用多个 NIC 获取所有外部 IP 地址 [英] Python, How to get all external ip addresses with multiple NICs

查看:25
本文介绍了Python,如何使用多个 NIC 获取所有外部 IP 地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用python获取具有多个网卡的机器的所有外部IP地址的最有效方法是什么?我知道需要一个外部服务器(我有一个可用的),但我无法找到一种方法来找到指定用于连接的网卡的好方法(所以我可以使用 for 循环来遍历各种网卡).关于解决此问题的最佳方法有什么建议吗?

解决方案

你应该使用 netifaces.它旨在在 Mac OS X、Linux 和 Windows 上跨平台.

<预><代码>>>>将 netifaces 导入为 ni>>>ni.interfaces()['lo', 'eth0', 'eth1', 'vboxnet0', 'dummy1']>>>ni.ifaddresses('eth0'){17: [{'广播': 'ff:ff:ff:ff:ff:ff', 'addr': '00:02:55:7b:b2:f6'}], 2: [{'广播': '24.19.161.7', 'netmask': '255.255.255.248', 'addr': '24.19.161.6'}], 10: [{'netmask': 'ffff:ffff:ffff:ffff::', '地址':'fe80::202:55ff:fe7b:b2f6%eth0'}]}>>>>>>ni.ifaddresses.__doc__'获取有关指定网络接口的信息. 返回一个字典,其键等于地址族常量, e.g.netifaces.AF_INET,其值是 该系列中附加到网络接口的地址列表.>>># eth0 的 IPv4 地址>>>ni.ifaddresses('eth0')[2][0]['addr']'24.19.161.6'

用于索引协议的数字来自 /usr/include/linux/socket.h(在 Linux 中)...

#define AF_INET 2/* Internet IP 协议 */#define AF_INET6 10/* IP 版本 6 */#define AF_PACKET 17/* 数据包族 */

What is the most efficient way to get all of the external ip address of a machine with multiple nics, using python? I understand that an external server is neeeded (I have one available) but am un able to find a way to find a good way to specify the nic to use for the connection (So I can use a for loop to iterate through the various nics). Any advice about the best way to go about this?

解决方案

You should use netifaces. It is designed to be cross-platform on Mac OS X, Linux, and Windows.

>>> import netifaces as ni
>>> ni.interfaces()
['lo', 'eth0', 'eth1', 'vboxnet0', 'dummy1']
>>> ni.ifaddresses('eth0')
{17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': '00:02:55:7b:b2:f6'}], 2: [{'broadcast': '24.19.161.7', 'netmask': '255.255.255.248', 'addr': '24.19.161.6'}], 10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::202:55ff:fe7b:b2f6%eth0'}]}
>>> 
>>> ni.ifaddresses.__doc__
'Obtain information about the specified network interface.

Returns a dict whose keys are equal to the address family constants,
e.g. netifaces.AF_INET, and whose values are a list of addresses in
that family that are attached to the network interface.'
>>> # for the IPv4 address of eth0
>>> ni.ifaddresses('eth0')[2][0]['addr']
'24.19.161.6'

The numbers used to index protocols are from /usr/include/linux/socket.h (in Linux)...

#define AF_INET         2       /* Internet IP Protocol         */
#define AF_INET6        10      /* IP version 6                 */
#define AF_PACKET       17      /* Packet family                */

这篇关于Python,如何使用多个 NIC 获取所有外部 IP 地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆