您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python,如何获取具有多个NIC的所有外部IP地址

Python,如何获取具有多个NIC的所有外部IP地址

您应该使用netifaces。它被设计为在Mac OS X,Linux和Windows上跨平台。

>>> import netifaces as ni
>>> ni.interfaces()
['lo', 'eth0', 'eth1', 'v@R_269_2419@net0', '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中)…

#define AF_INET         2       /* Internet IP Protocol         */
#define AF_INET6        10      /* IP version 6                 */
#define AF_PACKET       17      /* Packet family                */
python 2022/1/1 18:42:16 有255人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶