Python,如何使用多个 NIC 获取所有外部 ip 地址

标签 python networking ip nic

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

最佳答案

你应该使用 netifaces .它被设计为在 Mac OS X、Linux 和 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.\n\nReturns a dict whose keys are equal to the address family constants,\ne.g. netifaces.AF_INET, and whose values are a list of addresses in\nthat family that are attached to the network interface.'
>>> # for the IPv4 address of eth0
>>> ni.ifaddresses('eth0')[2][0]['addr']
'24.19.161.6'

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

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

关于Python,如何使用多个 NIC 获取所有外部 ip 地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8281371/

相关文章:

docker - 在 Docker 中, "Error response from daemon: could not choose an IP address to advertise since this system has multiple addresses on different interfaces"

python - 使用python3.5的aiohttp查询get URL的参数

python - Plotly:如何更改跟踪顺序,或在 plotly 中切换轴的边?

Python 机器人错误消息

Python-for语句理解

perl - 为什么我无法为 LWP::UserAgent 分配 IP?

http - 如何做 HTTP 等同于多播

networking - EC2-微型实例-网络响应/延迟/延迟非常慢

java - 配置 Spring Boot 以监听本地主机旁边的请求

python - Vagrant,Flask — 应用程序未在 10.10.10.10、127.0.0.1 上运行