如何使用Python列出所有本地接口和地址?

时间:2015-11-16 07:14:07

标签: python network-programming

人们希望能够在Python中列出所有接口及其地址的名称及其地址族。 Prithee,可以吗?

1 个答案:

答案 0 :(得分:0)

年轻的乡绅,确实可以。答案可以在这段代码中找到,这是对一些模块方法的快乐字典理解。

import netifaces

def interfaces():
    return {iface: {netifaces.address_families[k]: v
                    for k, v in netifaces.ifaddresses(iface).items()}
            for iface in netifaces.interfaces()}

interfaces()

{'awdl0': {'AF_INET6': [{'addr': 'fe80::fc13:3cff:fe9b:7fbd%awdl0',
                         'netmask': 'ffff:ffff:ffff:ffff::'}],
           'AF_LINK': [{'addr': 'fe:13:3c:9b:7f:bd'}]},
 'en0': {'AF_INET': [{'addr': '192.168.86.184',
                      'broadcast': '192.168.86.255',
                      'netmask': '255.255.255.0'}],
         'AF_INET6': [{'addr': 'fe80::aa66:7fff:fe0d:5e05%en0',
                       'netmask': 'ffff:ffff:ffff:ffff::'}],
         'AF_LINK': [{'addr': 'a8:66:7f:0d:5e:05'}]},
 'gif0': {},
 'lo0': {'AF_INET': [{'addr': '127.0.0.1',
                      'netmask': '255.0.0.0',
                      'peer': '127.0.0.1'}],
         'AF_INET6': [{'addr': '::1',
                       'netmask': 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff',
                       'peer': '::1'},
                      {'addr': 'fe80::1%lo0',
                       'netmask': 'ffff:ffff:ffff:ffff::'}]},
 'p2p0': {'AF_LINK': [{'addr': '0a:66:7f:0d:5e:05'}]},
 'stf0': {}}