How to convert a CIDR prefix to a dotted-quad netmask in Python?

匿名 (未验证) 提交于 2019-12-03 07:36:14

问题:

How can I convert a CIDR prefix to a dotted-quad netmask in Python?

For example, if the prefix is 12 I need to return 255.240.0.0.

回答1:

You can do it like this:

def cidr(prefix):     return socket.inet_ntoa(struct.pack(">I", (0xffffffff << (32 - prefix)) & 0xffffffff)) 


回答2:

Here is a solution on the lighter side (no module dependencies):

netmask = '.'.join([str((0xffffffff << (32 - len) >> i) & 0xff)                     for i in [24, 16, 8, 0]]) 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!