简体   繁体   English

需要分解IP子网

[英]Need to break down a IP subnet

I am trying to write a script which breaks down subnets larger(not greater than /16) than /24 to a /24 subnet. 我正在尝试编写一个脚本,它将比/ 24更大(不大于/ 16)的子网分解为/ 24子网。 Eg : 10.10.10.0/23 should give me 10.10.10.0/24 and 10.10.11.0/24 例如:10.10.10.0/23应该给我10.10.10.0/24和10.10.11.0/24

My logic is to first scan for the CIDR mask. 我的逻辑是首先扫描CIDR掩码。 if smaller than 24, then subtract that from 24 and that number(lets say x) gives the total number of /24s and then 1 to third octet of the IP x times and /24. 如果小于24,则从24减去该数字(假设x)给出/ x的总数,然后是IP x次和/ 24的1到3个八位字节。

eg: 10.10.8.0/22 例如:10.10.8.0/22

if 22 < 24 
x = 24-22 = 2
total # of /24s = 2^x = 4
So output :
10.10.8.0/24
10.10.9.0/24 
10.10.10.0/24
10.10.11.0/24

I am not sure how to code/modify the string for the third octet only and add 1 to the third octet only. 我不确定如何仅为第三个八位字节编码/修改字符串,并且仅将第三个八位字节添加1。

I am thinking of creating a list of all the third octet values and re constructing the IPs. 我正在考虑创建所有第三个八位字节值的列表并重新构建IP。 But if there is a simpler way out there, that would help me a lot !! 但是,如果有一个更简单的方法,这将帮助我很多!

Thanks ! 谢谢 !

Take a look at the netaddr package. 看一下netaddr包。 It already comes with built-in support for understanding net masks and is able to generate a list of subnets for any desired length: 它已经内置了对理解网络掩码的支持,并且能够生成任何所需长度的子网列表:

>>> n = netaddr.IPNetwork('10.10.8.0/22')
>>> list(n.subnet(24))
[IPNetwork('10.10.8.0/24'), IPNetwork('10.10.9.0/24'), IPNetwork('10.10.10.0/24'), IPNetwork('10.10.11.0/24')]
>>> [str(sn) for sn in n.subnet(24)]
['10.10.8.0/24', '10.10.9.0/24', '10.10.10.0/24', '10.10.11.0/24']

Since Python 3.3, this functionality is also available in the new built-in ipaddress module. 从Python 3.3开始,这个功能也可以在新的内置ipaddress模块中使用。

If you're using Python 3.3 or newer, you can use the ipaddress module . 如果您使用的是Python 3.3或更高版本,则可以使用ipaddress模块 Using the subnets method , you can do it in one line: 使用subnets方法 ,您可以在一行中执行此操作:

>>> list(ipaddress.ip_network('10.10.8.0/22').subnets(new_prefix=24))
[IPv4Network('10.10.8.0/24'), IPv4Network('10.10.9.0/24'), IPv4Network('10.10.10.0/24'), IPv4Network('10.10.11.0/24')]

Converting to strings is trivial. 转换为字符串是微不足道的。 Just cast to str . 刚刚施展到str

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM