Skip to content

Instantly share code, notes, and snippets.

@wido
Last active May 31, 2023 18:43
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save wido/af7811113a5d1a9a2fe6448954839d33 to your computer and use it in GitHub Desktop.
Save wido/af7811113a5d1a9a2fe6448954839d33 to your computer and use it in GitHub Desktop.
Generate a random IPv6 address
#!/usr/bin/env python3
"""
Generate a random IPv6 address for a specified subnet
"""
from random import seed, getrandbits
from ipaddress import IPv6Network, IPv6Address
subnet = '2001:db8:100::/64'
seed()
network = IPv6Network(subnet)
address = IPv6Address(network.network_address + getrandbits(network.max_prefixlen - network.prefixlen))
print(address)
@json-m
Copy link

json-m commented Oct 23, 2018

It would be very useful if this is modified to give X amount of IPv6 IPs? for example it would generate 1000 IPv6 IPs starting from the lowest range. or does such script already exist?

$ for ip in {1..1000}; do python random-ipv6-addr.py ; done ? not exactly what you asked for but you can work from there..

Copy link

ghost commented May 31, 2023

Here's a way to generate them a bit faster

from random import getrandbits
from socket import inet_ntop, AF_INET6
from struct import pack

def random_ipv6():
    return inet_ntop(AF_INET6, pack('>QQ', getrandbits(64), getrandbits(64)))
    
for _ in range(400):
    print(random_ipv6())

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment