Вы можете сделать это, используя стандартные модули random
и ipaddress
. Короткая версия:
from ipaddress import IPv6Network
import random
ula = IPv6Network("fd00::/8")
random_network = IPv6Network((
ula.network_address + (random.getrandbits(64 - ula.prefixlen) << 64 ),
64))
Более длинная версия с объяснением:
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))