How To Increment And Get The Next Ipv6 Network Address From The Current Network Address
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 w
Solution 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
classBetterIPv6Network(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))
defsize(self):
"""Return network size."""return1 << (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::/324001:2::/324001:3::/32
Python 3.4:
Python 3.4 did not accept tuples to init ipaddress.IPv6Network. This code will work around that.
import ipaddress
classBetterIPv6Network(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])
defsize(self):
"""Return network size."""return1 << (self.max_prefixlen - self.prefixlen)
Post a Comment for "How To Increment And Get The Next Ipv6 Network Address From The Current Network Address"