如何从当前网络地址递增并获取下一个IPv6网络地址 [英] How to increment and get the next IPv6 network address from the current network address

查看:83
本文介绍了如何从当前网络地址递增并获取下一个IPv6网络地址的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用标准的python软件包,如果我们提供任何IPv6网络地址作为输入,如何获得下几个IPv6网络地址.基本上,我想遍历给定的网络地址,并且在每次迭代时都应该递增并获得下一个网络

Using standard python packages, how can I get the next few IPv6 network address if we give any IPv6 network address as input. Basically I want to iterate over the network address which was given and on each iteration it should increment and get the next network

例如,如果我的起始网络地址为4001:1 ::/32,那么在每次迭代中,我都希望获得下一个网络地址为4001:2 ::/32,4001:3 ::/32,4001 :4 ::/32等等.

For example, if my start network address 4001:1::/32, then on each iteration I would like to get the next network address as 4001:2::/32, 4001:3::/32, 4001:4::/32 and so on.

>>> inet = iterate_on('4001:1::/32')
>>> next(inet)
4001:2::/32
>>> next(inet)
4001:3::/32

注意:这是我以前对推荐答案

ipcalc 有使IP地址上的数学相当容易的例程.但是,如果最好不要安装ipcalc,则可以构造一个从ipaddress.IPv6Network继承的类.

The library ipcalc has routines to make math on ip addresses fairly easy. But if it would be preferable to not install ipcalc, a class that inherits from ipaddress.IPv6Network can be constructed.

import ipaddress

class BetterIPv6Network(ipaddress.IPv6Network):

    def __add__(self, offset):
        """Add numeric offset to the IP."""
        new_base_addr = int(self.network_address) + offset
        return self.__class__((new_base_addr, self.prefixlen))

    def size(self):
        """Return network size."""
        return 1 << (self.max_prefixlen - self.prefixlen)

测试代码:

import itertools as it
network = BetterIPv6Network(u'4001:1::/32')
network_addrs = (network + i * network.size() for i in it.count())
print(next(network_addrs))
print(next(network_addrs))
print(next(network_addrs))

结果:

4001:1::/32
4001:2::/32
4001:3::/32

Python 3.4:

Python 3.4不接受元组来初始化ipaddress.IPv6Network.这段代码可以解决这个问题.

Python 3.4:

Python 3.4 did not accept tuples to init ipaddress.IPv6Network. This code will work around that.

import ipaddress

class BetterIPv6Network(ipaddress.IPv6Network):

    def __add__(self, offset):
        """Add numeric offset to the IP."""
        new_base_addr = int(self.network_address) + offset
        new_base_addr_str = str(self.__class__(new_base_addr)).split('/')[0]
        return self.__class__(
            new_base_addr_str + '/' + str(self).split('/')[1])

    def size(self):
        """Return network size."""
        return 1 << (self.max_prefixlen - self.prefixlen)

这篇关于如何从当前网络地址递增并获取下一个IPv6网络地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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