Python 3: ipaddr/netaddr模块

4 投票
3 回答
26339 浏览
提问于 2025-04-15 22:02

我觉得我可能做错了什么……现在我正在尝试验证一个IP地址是否在特定的子网内,想用一个内置模块来实现。

我使用的是activepython:

ActivePython 3.1.2.3 (ActiveState Software Inc.) based on
Python 3.1.2 (r312:79147, Mar 22 2010, 12:20:29) [MSC v.1500 32 bit (Intel)] on win32

在更新日志中有提到这些内容:

Python News
(editors: check NEWS.help for information about editing NEWS using ReST.)

What's New in Python 3.1.2?
Release date: 2010-03-20

----- snip -----

Removed the ipaddr module. 
Issue #3613: base64.{encode,decode}string are now called 
System Message: WARNING/2 (, line 706)

----- snip -----

Issue #3959: The ipaddr module has been added to the standard library. Contributed by Google.

通过这些和其他的谷歌搜索,我认为ipaddr是一个内置模块,但实际上:

>>> import ipaddr
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named ipaddr
>>> from ipaddr import *
Traceback (most recent call last):
  File "", line 1, in 
ImportError: No module named ipaddr

所以我想安装netaddr并尝试使用它,但从netaddr得到的结果是:

>>> import netaddr
Traceback (most recent call last):
  File "", line 1, in 
  File "C:\Python31\lib\site-packages\netaddr\__init__.py", line 18, in 
    from netaddr.ip import IPAddress, IPNetwork, IPRange, all_matching_cidrs, \
  File "C:\Python31\lib\site-packages\netaddr\ip\__init__.py", line 1877, in 
    IPV6_LOOPBACK = IPAddress('::1')
  File "C:\Python31\lib\site-packages\netaddr\ip\__init__.py", line 262, in __init__
    self.value = addr
  File "C:\Python31\lib\site-packages\netaddr\ip\__init__.py", line 292, in _set_value
    % value)
netaddr.core.AddrFormatError: failed to detect IP version: '::1'

我感到相当沮丧,不知道接下来该怎么办……有什么建议吗?

3 个回答

2

模块 ipaddress 是在 Python 3.3 版本中引入的,它是 ipaddr 模块的新版本。

ipaddress 和 PyPI 上的 ipaddr 模块不兼容,也就是说它们不能直接互换使用。

主要的区别有:

  • ipaddress 的 *Network 类相当于 ipaddr 的 *Network 类,但它的严格标志设置为 True。
  • ipaddress 的 *Interface 类相当于 ipaddr 的 *Network 类,但它的严格标志设置为 False。
  • ipaddress 中的一些工厂函数被重命名,以便和类区分开来。
  • 有一些属性也被重命名,以更清楚地说明它们的用途。(例如:network, network_address)
    • 在 ipaddr 中返回容器的一些方法和函数现在返回的是迭代器。这包括子网、地址排除、地址范围汇总和地址列表合并等。

想了解更多信息,可以查看 PEP-3144

3

在3.1版本的开发过程中(在alpha 2和beta 1之间),添加了一个叫做ipaddr的模块,但在3.1的第一个候选版本发布之前就被删掉了。所以这个模块并不属于任何已发布的Python版本的标准库。不过,你还是可以从比如说PyPI上下载和安装它。

关于netaddr的错误,似乎是netaddr模块本身的问题。它尝试检测是否支持IPv6,但失败了。我猜这可能是模块里的一个bug,不过要找到解决办法或者替代方案就比较难了。

4

netaddr 目前还不支持 Python 3.x(在自述文件中有提到)。

不过,在即将发布的版本(0.7.5)中会支持。我觉得这提醒我应该加快速度,把它发布出去!

我在项目的错误跟踪系统上添加了一个问题记录,链接在这里:

http://code.google.com/p/netaddr/issues/detail?id=55

谢谢。

撰写回答