你应该使用网络面孔 http://pypi.python.org/pypi/netifaces/。它被设计为跨平台的,包含适用于 Windows 的专用代码以及在不同 UNIX/类 UNIX 平台上工作的各种通用版本。
As of 网络面孔 http://pypi.python.org/pypi/netifaces/版本0.10.0,支持Python3。
使用总结
>>> from netifaces import AF_INET, AF_INET6, AF_LINK, AF_PACKET, AF_BRIDGE
>>> import netifaces as ni
>>> ni.interfaces()
['lo', 'eth0', 'eth1', 'vboxnet0', 'dummy1']
>>>
>>> ni.ifaddresses('eth0')[AF_LINK] # NOTE: AF_LINK is an alias for AF_PACKET
[{'broadcast': 'ff:ff:ff:ff:ff:ff', 'addr': '00:02:55:7b:b2:f6'}]
>>> ni.ifaddresses('eth0')[AF_INET]
[{'broadcast': '172.16.161.7', 'netmask': '255.255.255.248', 'addr': '172.16.161.6'}]
>>>
>>> # eth0 ipv4 interface address
>>> ni.ifaddresses('eth0')[AF_INET][0]['addr']
'172.16.161.6'
>>>>
Details
Windows 支持:
大多数 MS Windows 安装不需要编译器。如果您收到有关安装 MS Visual C++ for Windows 的警告,请非常小心 https://stackoverflow.com/questions/2817869/error-unable-to-find-vcvarsall-bat#comment23311731_10558328因为你需要将用于 python 的编译器版本与用于模块的编译器版本相匹配。
详细示例网络面孔 http://pypi.python.org/pypi/netifaces/数据结构:
>>> 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': '172.16.161.7',
'netmask': '255.255.255.248',
'addr': '172.16.161.6'
}
],
10: [
{
'netmask': 'ffff:ffff:ffff:ffff::',
'addr': 'fe80::202:55ff:fe7b:b2f6%eth0'
}
]
}
>>>
>>> print(ni.ifaddresses.__doc__)
Obtain information about the specified network interface.
Returns a dict whose keys are equal to the address family constants,
e.g. netifaces.AF_INET, and whose values are a list of addresses in
that family that are attached to the network interface.
>>>
>>> # for the IPv4 address of eth0
>>> ni.ifaddresses('eth0')[2][0]['addr']
'172.16.161.6'
用于索引协议的数字来自/usr/include/linux/socket.h
(在 Linux 中)...EDIT:我的 3.2 内核有它们:/usr/src/linux-headers-3.2.0-4-common/include/linux/socket.h
#define AF_INET 2 /* Internet IP Protocol */
#define AF_INET6 10 /* IP version 6 */
#define AF_PACKET 17 /* Packet family */
好消息是您不必记住所有这些标头常量,它们包含在网络面孔 http://pypi.python.org/pypi/netifaces/:
>>> from netifaces import AF_INET, AF_INET6, AF_LINK, AF_PACKET, AF_BRIDGE
>>> import netifaces as ni