当我有多个NIC时,如何确定我的所有IP地址? [英] How do I determine all of my IP addresses when I have multiple NICs?

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

问题描述

我的计算机上有多个网络接口卡,每个都有其自己的IP地址.

I have multiple Network Interface Cards on my computer, each with its own IP address.

当我使用Python(内置)socket模块中的gethostbyname(gethostname())时,它将仅返回其中之一.我如何获得其他人?

When I use gethostbyname(gethostname()) from Python's (built-in) socket module, it will only return one of them. How do I get the others?

推荐答案

使用 netifaces 模块.由于网络很复杂,因此使用netifaces可能会有些棘手,但是以下是您要执行的操作:

Use the netifaces module. Because networking is complex, using netifaces can be a little tricky, but here's how to do what you want:

>>> import netifaces
>>> netifaces.interfaces()
['lo', 'eth0']
>>> netifaces.ifaddresses('eth0')
{17: [{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': '00:11:2f:32:63:45'}], 2: [{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}], 10: [{'netmask': 'ffff:ffff:ffff:ffff::', 'addr': 'fe80::211:2fff:fe32:6345%eth0'}]}
>>> for interface in netifaces.interfaces():
...   print netifaces.ifaddresses(interface)[netifaces.AF_INET]
...
[{'peer': '127.0.0.1', 'netmask': '255.0.0.0', 'addr': '127.0.0.1'}]
[{'broadcast': '10.0.0.255', 'netmask': '255.255.255.0', 'addr': '10.0.0.2'}]
>>> for interface in netifaces.interfaces():
...   for link in netifaces.ifaddresses(interface)[netifaces.AF_INET]:
...     print link['addr']
...
127.0.0.1
10.0.0.2

可以这样使它更具可读性:

This can be made a little more readable like this:

from netifaces import interfaces, ifaddresses, AF_INET

def ip4_addresses():
    ip_list = []
    for interface in interfaces():
        for link in ifaddresses(interface)[AF_INET]:
            ip_list.append(link['addr'])
    return ip_list

如果要使用IPv6地址,请使用AF_INET6而不是AF_INET.如果您想知道为什么netifaces到处都使用列表和词典,那是因为一台计算机可以有多个NIC,并且每个NIC可以有多个地址,并且每个地址都有自己的一组选项.

If you want IPv6 addresses, use AF_INET6 instead of AF_INET. If you're wondering why netifaces uses lists and dictionaries all over the place, it's because a single computer can have multiple NICs, and each NIC can have multiple addresses, and each address has its own set of options.

这篇关于当我有多个NIC时,如何确定我的所有IP地址?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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