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

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

问题描述

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

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?

推荐答案

你应该使用 netifaces 。它设计为在Mac 操作系统X,Linux和Windows上实现跨平台。

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.\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'

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

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天全站免登陆