Python 3:根据 CIDR 表示法创建可能的 IP 地址列表
我接到的任务是在 python (3.1) 中创建一个函数,该函数将采用 CIDR 表示法并返回可能的 IP 地址列表。我浏览了 python.org 并发现了这个: http://docs.python.org/dev/py3k/library/ipaddr.html
但我还没有看到任何可以满足这一需求的东西...如果有人愿意为我提供任何帮助,我将非常感激。提前致谢。 :-)
I have been handed the task of creating a function in python (3.1) that will take a CIDR notation and return the list of possible ip addresses. I have looked around python.org and found this:
http://docs.python.org/dev/py3k/library/ipaddr.html
but i haven't seen anything that will fill this need... I would be very grateful for any assistance anyone cares to kick my way. thanks in advance. :-)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
在 Python 3 中就像这样简单
In Python 3 as simple as
如果您不习惯使用内置模块,可以使用一个名为 netaddr 的项目这是我用于处理 IP 网络的最佳模块。
请查看IP 教程,其中说明了使用网络和辨别他们的IP。简单的例子:
If you aren't married to using the built-in module, there is a project called netaddr that is the best module I have used for working with IP networks.
Have a look at the IP Tutorial which illustrates how easy it is working with networks and discerning their IPs. Simple example:
我宁愿做一点数学运算,也不愿安装外部模块,没有人和我有同样的品味吗?
I would prefer to do a little math rather than to install an external module, no one has the same taste with me?
您是否检查过
iptools
?这似乎是一个相当不错的选择。Have you checked out
iptools
? It seems to be a fairly good fit.如果你对 python 逻辑不感兴趣,我们可以使用 Python 的 ipaddress lib 来获取它。除此之外,上述解决方案就足够了。
We can get this by using ipaddress lib of Python if you are not interested in playing with python logics. Else above solutions are enough.
它不在文档中,但浏览源代码表明 ipaddr 实现了 __iter__ 和 iterhosts,这正是您想要的。
呃,没关系。
ipaddr.py
已在 3.1 beta 中添加到 stdlib,但在 3.1 rc 中被删除。你可以将后者捆绑在一起。
It's not in the documentation, but browsing the source suggests that
ipaddr
implements__iter__
anditerhosts
, which is exactly what you want.Err, nevermind.
ipaddr.py
was added to stdlib in 3.1 beta, but removed by 3.1 rc.You could just bundle the latter.
下面的代码将根据提供的 IP 和子网生成 IP 范围。展开 CIDR 表示法,例如 (255.255.255.0)
Below code will generate range of IPs on providing IP and subnet. Expand the CIDR notation like(255.255.255.0)