从Python中的IP地址和掩码长度获取IP掩码 [英] Get IP Mask from IP Address and Mask Length in Python

查看:461
本文介绍了从Python中的IP地址和掩码长度获取IP掩码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以点分四元符号给出IP地址,例如:
192.192.45.1
掩码长度通常为8、16、24,但可以是任何长度,即17.

Given an IP Address in dotted quad notation, for example:
192.192.45.1
And a mask length for example 8, 16, 24 typically, but could be anything i.e. 17.

有人可以提供python中的代码来计算子网掩码吗?最好我 可以将结果作为32位整数来获取,因此很容易进行哈希处理,然后在需要打印时将其重新解释为点分四边形.我看到python有一个套接字库,它基本上是unix套接字api的包装器.我还看到它具有函数inet_ntoa(), 但它返回某种数据包结构.我对Python struct库不是很熟悉,所以我希望其他人有一些想法.谢谢!

Can somebody please provide the code in python to calculate the subnet mask? Preferably I could get the result as 32-bit integer so that it is easy to hash and then reinterpret as dotted quad when necessary for printing. I see that python has a socket library which is basically a wrapper around the unix socket api. I also saw it has the function inet_ntoa(), but it returns some sort of packet struct. I'm not terribly familiar with the Python struct library, so I was hoping some other would have some ideas. Thanks!

推荐答案

最简单的方法是使用Google的 ipaddr 模块.我假设下面有一个25位的掩码,但是正如您所说的,它可以是任何东西

The simplest way is to use google's ipaddr module. I assume a 25 bit mask below, but as you say, it could be anything

>>> import ipaddr
>>> mask = ipaddr.IPv4Network('192.192.45.1/25')
>>> mask.netmask
IPv4Address('255.255.255.128')
>>>

该模块在处理IPv4和IPv6地址方面非常有效...其中一些其他功能的示例...

The module is rather efficient at manipulating IPv4 and IPv6 addresses... a sample of some other functionality in it...

>>> ## Subnet number?
>>> mask.network
IPv4Address('192.192.45.0')
>>>
>>> ## RFC 1918 space?
>>> mask.is_private
False
>>>
>>  ## The subnet broadcast address
>>> mask.broadcast
IPv4Address('192.192.45.127')
>>> mask.iterhosts()
<generator object iterhosts at 0xb72b3f2c>

这篇关于从Python中的IP地址和掩码长度获取IP掩码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆