简体   繁体   English

以CIDR格式获取下一个子网

[英]get next subnet in CIDR format

I have the following:- 我有以下内容:

start_range = "10.40.0.0/16" start_range =“ 10.40.0.0/16”

end_range = "10.100.0.0/16" end_range =“ 10.100.0.0/16”

I have to write a logic to iterate over all possible ranges(with same subnet mask /16) from start to end . 我必须写一个逻辑遍历所有可能的范围(具有相同的子网掩码/ 16)从startend For each subnet I will be doing some processing and then continuing to the next one. 对于每个子网,我将进行一些处理,然后继续进行下一个处理。

I could achieve this in trivial way where I know, I have to increment last network octate(ie increment 40 to 41 -> 42 -> 43 and so on). 在我知道的地方,我可以通过琐碎的方式实现这一点,我必须递增最后一个网络八进制(即递增40至41-> 42-> 43,依此类推)。

start_subnet = "10.40.0.0/16"
end_subnet = "10.100.0.0/16"


start_val = int(start_subnet.split(".")[1])
end_val = int(end_subnet.split('.')[1])
subnet_split = start_subnet.split(".")
subnet_split[1] = "{}"
subnet_proto = ".".join(subnet_split)  # "10.{}.0.0/16"

for i in range(start_val, end_val+1):  # iterate from 40 to 100
    cur_subnet = subnet_proto.format(i)   # "10.40.0.0/16", "10.41.0.0/16" etc
    # do processing on cur_subnet

Is there a better(Pythonic) way to get the next subnet(in CIDR format). 有没有更好的方法(Pythonic)来获取下一个子网(CIDR格式)。 May be netaddr module has something I am not aware of? 可能是netaddr模块有我不知道的东西吗?

This might be what you have in mind (not really well thought-through or tested, you've been warned!). 这可能就是您要记住的(没有经过深思熟虑或经过测试,已经警告您!)。

The ipaddress module is from python3 but it has a backport, just run ipaddress模块​​来自python3,但是它有一个backport,可以运行

pip install ipaddress

to get it. 为拿到它,为实现它。

import ipaddress


def subnet_range(start_subnet, end_subnet):
    start = ipaddress.ip_network(unicode(start_subnet))
    end = ipaddress.ip_network(unicode(end_subnet))
    assert start.prefixlen == end.prefixlen
    ranges = [
        n
        for ipaddr in ipaddress.summarize_address_range(
            list(start)[0],
            list(end)[0])
        for n in ipaddr.subnets(new_prefix=start.prefixlen)][:-1]
    ranges.append(end)
    return ranges


if __name__ == "__main__":
    start_subnet = "9.250.0.0/16"
    end_subnet = "10.100.0.0/16"


for r in subnet_range(start_subnet, end_subnet):
    print r

Following usage of netaddr helped me to get the expected result. 以下netaddr使用帮助我获得了预期的结果。

from netaddr import IPNetwork

start_range = IPNetwork("10.40.0.0/16")
end_range = IPNetwork("10.45.0.0/16")
allowed_range = []

while start_range<=end_range:
    allowed_range.append(start_range)
    start_range = start_range.next()

print allowed_range

This would print the following:- 这将打印以下内容:

[IPNetwork('10.40.0.0/16'), IPNetwork('10.41.0.0/16'),
IPNetwork('10.42.0.0/16'), IPNetwork('10.43.0.0/16'),
IPNetwork('10.44.0.0/16'), IPNetwork('10.45.0.0/16')]

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

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