How to increment and get the next IPv6 network address from the current network address

送分小仙女□ 提交于 2019-12-14 02:28:16

问题


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

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

Note: Here is my previous question for fetching IPv4 networks.


回答1:


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.

Code

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)

Test Code:

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))

Results:

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

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)


来源:https://stackoverflow.com/questions/44363103/how-to-increment-and-get-the-next-ipv6-network-address-from-the-current-network

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