til icon indicating copy to clipboard operation
til copied to clipboard

Find an unassigned subnet

Open xluffy opened this issue 2 years ago • 0 comments

#!/usr/bin/env python3

from netaddr import *
import math


def main():
    """
    Main function
    """
    cidr = "10.0.0.0/8"
    assigned = [
        "10.100.0.0/20",
        "10.100.128.0/20",
        "10.100.160.0/20",
        "10.100.192.0/20",
        "10.100.208.0/20",
        "10.100.224.0/20",
        "10.100.240.0/20",
        "10.100.32.0/20",
        "10.100.64.0/20",
        "10.100.96.0/20",
        "10.101.0.0/16",
        "10.102.0.0/16",
        "10.103.0.0/16",
        "10.104.0.0/16",
        "10.105.0.0/16",
        "10.106.0.0/16",
        "10.107.0.0/16",
        "10.108.0.0/16",
        "10.109.0.0/16",
        "10.110.0.0/16",
        "10.111.0.0/16",
        "10.112.0.0/16",
        "10.113.0.0/16",
        "10.114.0.0/16",
        "10.115.0.0/16",
        "10.116.0.0/16",
        "10.117.0.0/16",
        "10.118.0.0/16",
        "10.119.0.0/16",
        "10.199.0.0/16",
        "10.201.0.0/20",
        "10.201.128.0/20",
        "10.201.144.0/20",
        "10.201.192.0/20",
        "10.201.208.0/20",
        "10.201.224.0/20",
        "10.201.240.0/20",
        "10.201.32.0/20",
        "10.201.64.0/20",
        "10.202.128.0/20",
        "10.202.192.0/20",
        "10.202.32.0/20",
        "10.205.0.0/16",
        "10.212.0.0/16",
        "10.0.0.0/16",
        "10.1.0.0/16",
        "10.2.0.0/16",
        "10.3.0.0/16",
        "10.4.0.0/16",
        "10.5.0.0/16",
        "10.6.0.0/16",
        "10.7.0.0/16",
        "10.8.0.0/16",
        "10.9.0.0/16",
        "10.12.0.0/16",
        "10.13.0.0/16",
        "10.14.0.0/16",
        "10.10.0.0/16",
        "10.11.0.0/16",
        "10.70.0.0/16",
    ]

    # number IP need to assigned
    needed_ips = 4096
    available = IPSet([cidr]) - IPSet(assigned)
    needed_prefix = 32 - math.ceil(math.log2(needed_ips))

    for net in available.iter_cidrs():
        if net.prefixlen <= needed_prefix:
            print(next(net.subnet(needed_prefix, 1)))


if __name__ == "__main__":
    main()

Ref: https://stackoverflow.com/a/43082332

xluffy avatar Jan 12 '23 07:01 xluffy