How to generate random IPv6 addresses in a given network using Python
This code generates random IPv6 addresses in a given network using Python’s ipaddress module:
import ipaddress
import random
def random_ipv6_addr(network):
"""
Generate a random IPv6 address in the given network
Example: random_ipv6_addr("fd66:6cbb:8c10::/48")
Returns an IPv6Address object.
"""
net = ipaddress.IPv6Network(network)
# Which of the network.num_addresses we want to select?
addr_no = random.randint(0, net.num_addresses)
# Create the random address by converting to a 128-bit integer, adding addr_no and converting back
network_int = int.from_bytes(net.network_address.packed, byteorder="big")
addr_int = network_int + addr_no
addr = ipaddress.IPv6Address(addr_int.to_bytes(16, byteorder="big"))
return addr
# Usage example
print(random_ipv6_addr("fdce:4879:a1e9::/48"))
# Prints e.g. fdce:4879:a1e9:e351:1a01:be9:4d9a:157d
It works by first converting the IPv6 network address to binary and then adding a random host number. After that, it will be converted back to an IPv6Address
object.