Search code examples
python-3.xipv6

How to generate a random IPv6 subnet in Python 3


I have an existing IPv6 address block. How can I generate a random /64 network in this block using Python, preferably without using any external libraries?

As an example, you can start from the fd00::/8 Unique Local Address (ULA) block to generate a random private ipv6 network.


Solution

  • You can do this using the standard random and ipaddress modules. Short version:

    from ipaddress import IPv6Network
    import random
    
    ula = IPv6Network("fd00::/8")
    random_network = IPv6Network((
        ula.network_address + (random.getrandbits(64 - ula.prefixlen) << 64 ),
        64))
    

    Longer version with explanation:

    from ipaddress import IPv6Network
    import random
    
    # Start from the ula address block
    ula = IPv6Network("fd00::/8")
    
    # Get a random bitstring the size of the number of bits we can randomise.
    # This is the number of bits reserved for the network (64) minus the number of bits
    # already used in the address block we start from (8).
    random_bits = random.getrandbits(64 - ula.prefixlen)
    
    # Bitshift those bits 64 times to the left, so the last 64 bits are zero.
    random_address_suffix = random_bits << 64
    
    # Add those bits to the network address of the block we start from
    # and create a new IPv6 network with the modified address and prefix 64
    random_network = IPv6Network((
        ula.network_address + random_address_suffix,
        64))