Get IP Mask from IP Address and Mask Length in Python

好久不见. 提交于 2019-11-30 15:40:00
Mike Pennington

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')
>>>

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>

You can calcuate the 32 bit value of the mask like this

(1<<32) - (1<<32>>mask_length)

eg.

>>> import socket, struct
>>> mask_length = 24
>>> mask = (1<<32) - (1<<32>>mask_length)
>>> socket.inet_ntoa(struct.pack(">L", mask))
'255.255.255.0'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!