跳转到主要内容

跨平台网络接口和IP地址枚举库

项目描述

https://github.com/pydron/ifaddr/workflows/CI/badge.svg https://img.shields.io/pypi/v/ifaddr.svg https://codecov.io/gh/pydron/ifaddr/branch/master/graph/badge.svg

ifaddr 是一个小型的Python库,允许您查找计算机的所有以太网和IP地址。它在 LinuxOS XWindows 上进行了测试。其他BSD衍生版如 OpenBSDFreeBSDNetBSD 也应该可以正常工作,但我还没有亲自测试过这些。 Solaris/Illumos 也应该可以。

此库是开源的,并使用MIT许可证发布。它适用于Python 3.7+。

您可以使用 pip install ifaddr 安装它。它不需要编译任何东西,所以不应该有任何惊喜。即使在Windows上。

项目链接

让我们开始吧!

import ifaddr

adapters = ifaddr.get_adapters()

for adapter in adapters:
    print("IPs of network adapter " + adapter.nice_name)
    for ip in adapter.ips:
        print("   %s/%s" % (ip.ip, ip.network_prefix))

这将打印

IPs of network adapter H5321 gw Mobile Broadband Driver
   IP ('fe80::9:ebdf:30ab:39a3', 0L, 17L)/64
   IP 169.254.57.163/16
IPs of network adapter Intel(R) Centrino(R) Advanced-N 6205
   IP ('fe80::481f:3c9d:c3f6:93f8', 0L, 12L)/64
   IP 192.168.0.51/24
IPs of network adapter Intel(R) 82579LM Gigabit Network Connection
   IP ('fe80::85cd:e07e:4f7a:6aa6', 0L, 11L)/64
   IP 192.168.0.53/24
IPs of network adapter Software Loopback Interface 1
   IP ('::1', 0L, 0L)/128
   IP 127.0.0.1/8

您将同时获得IPv4和IPv6地址。后者包括flowinfo和scope_id。

如果您想包括没有配置IP地址的网络接口,请将 include_unconfigured 参数传递给 get_adapters()。没有配置IP地址的适配器将具有零长度的 ips 属性。例如

import ifaddr

adapters = ifaddr.get_adapters(include_unconfigured=True)

for adapter in adapters:
    print("IPs of network adapter " + adapter.nice_name)
    if adapter.ips:
        for ip in adapter.ips:
            print("   %s/%s" % (ip.ip, ip.network_prefix))
    else:
        print("  No IPs configured")

变更日志

0.2.0

  • 添加了一个包含无IP适配器的选项,归功于内存

  • 修复了在Windows上接口名称为 bytes 而不是 str 的错误

  • 添加了 netifaces.interfaces() 的实现(通过 ifaddr.netifaces.interfaces() 可用)

  • 添加了类型提示

向后不兼容/破坏性更改

  • 停止支持Python 3.6

0.1.7

  • 修复了示例中的Python 3兼容性问题,感谢Tristan Stenner和Josef Schlehofer

  • 在Adapter.index中公开了网络接口索引,感谢Dmitry Tantsur

  • 将许可证文件添加到PyPI上的发行版,感谢Tomáš Chvátal

  • 根据Jorge Schrauwen提出的补丁修复了Illumos/Solaris兼容性

  • 设置了通用wheels,从现在起ifaddr将在PyPI上同时提供源和wheel发行版

替代方案

Alastair Houghton开发了netifaces,它可以做这个库能做的一切,还能更多。唯一的缺点是它需要编译,这可能使安装变得困难。

从ifaddr 0.2.0开始,我们实现了 netifaces.interfaces() 的等价功能。它通过 ifaddr.netifaces.interfaces() 可用。

支持者

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误记录 StatusPage StatusPage 状态页面