如何在Python 3中生成随机IPv6子网

问题描述 投票:0回答:3

我有一个现有的 IPv6 地址块。如何使用 Python 在此块中生成随机

/64
网络,最好不使用任何外部库?

作为示例,您可以从

fd00::/8
唯一本地地址 (ULA) 块开始生成随机私有 ipv6 网络。

python-3.x ipv6
3个回答
1
投票

正如 @Ron Maupin 在他们对 OP 答案的评论中所指出的,这里有一个使用正确数量的随机位的解决方案:

#! /usr/bin/env python3
"""IPv6 ULA generation."""

from ipaddress import IPv6Network
from random import getrandbits


__all__ = ['get_ula_network']


ULA_BASE = IPv6Network("fd00::/8")


def get_ula_network() -> IPv6Network:
    """Generates a random ULA network."""

    random_suffix = getrandbits(40) << 80
    base_address = ULA_BASE.network_address + random_suffix
    return IPv6Network((base_address, 48))

您可以使用以下方式驱动上述

/64
网络:

>>> network = get_ula_network()
>>> subnets = list(network.subnets(new_prefix=64))
>>> len(subnets)
65536
>>> 

0
投票

您可以使用标准

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))

0
投票

基于此处已有的答案,生成一个可配置的

/64
独特子网列表的函数(这可能是大多数人正在寻找的)

#! /usr/bin/env python3

from ipaddress import IPv6Network
from random import getrandbits, randrange

def get_ula_subnets(num_subnets=1) -> IPv6Network:
    """Generate random IPv6 ULA /64 subnets
    """
    count = 0
    subnet_list = []
    ula_base = IPv6Network("fd00::/8")
    random_suffix = getrandbits(40) << 80
    base_address = ula_base.network_address + random_suffix
    network = IPv6Network((base_address, 48))
    subnets = list(network.subnets(new_prefix=64))

    # do not use 'is not' for comparisons above 256
    while count != num_subnets:
        random_iter = randrange(65536)
        random_subnet = subnets[random_iter]

        if random_subnet not in subnet_list:
            print(random_subnet)
            subnet_list.append(random_subnet)

        count = len(subnet_list)

    print (len(subnet_list))
    return subnet_list

subnets = get_ula_subnets(300)

© www.soinside.com 2019 - 2024. All rights reserved.