在python中将cidr转换为子网掩码 [英] convert cidr to subnet mask in python

查看:219
本文介绍了在python中将cidr转换为子网掩码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个已创建的python字典,该字典包含以下格式的子网列表:

I have a python dictionary that I've created, this dictionary contains a list of subnets in the following format:

x.x.x.x/24
y.y.y,y/25
z.z.z.z/26
a.a.a.a/27 

等...

我想把这本词典中的项目拿出来,解析它,然后以以下格式吐出结果:

I would like to take the items in this dictionary, parse it, then spit out the results in the following format:

x.x.x.x 255.255.255.0
y.y.y.y 255.255.255.128
x.x.x.x 255.255.255.192
a.a.a.a 255.255.255.224 

由于我在网络上找不到太多关于此主题的信息,因此到目前为止,我对此并没有太多了解,也没有什么可以快速简洁地实现.有什么想法吗?

I don't have much on this as of right now because I can't find a lot on this topic on the web, not anything that can be in a quick and concise way that is. Thoughts?

推荐答案

代码:

import socket
import struct

def cidr_to_netmask(cidr):
    network, net_bits = cidr.split('/')
    host_bits = 32 - int(net_bits)
    netmask = socket.inet_ntoa(struct.pack('!I', (1 << 32) - (1 << host_bits)))
    return network, netmask

用法:

>>> cidr_to_netmask('10.10.1.32/27')
('10.10.1.32', '255.255.255.224')
>>> cidr_to_netmask('208.128.0.0/11')
('208.128.0.0', '255.224.0.0')
>>> cidr_to_netmask('208.130.28.0/22')
('208.130.28.0', '255.255.252.0')

这篇关于在python中将cidr转换为子网掩码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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