Generate IP Addresses and valid CIDR notations
I needed to test some networking tools I've been developing, and to do that I needed IP addresses. To get IP addresses I wrote this snippet.
#!/usr/bin/python import random def generate_ip(): CLASSES='ABC' ip_class = random.choice(CLASSES) if ip_class == "A": first_octet = random.randint(1,126) if ip_class == "B": first_octet = random.randint(128,191) if ip_class == "C": first_octet = random.randint(192,223) second_octet = random.randint(0,254) third_octet = random.randint(0,254) fourth_octet = random.randint(0,254) return "%i.%i.%i.%i" %(first_octet,second_octet,third_octet,fourth_octet)
I also needed to generate random valid slash notations for a given ip:
def generate_cidr(network_id): first_octet = int(str(network_id).split(".")[0]) if first_octet <= 126 and first_octet >= 1: cidr_bits = random.randint(8,30) if first_octet >=127 and first_octet <= 191: cidr_bits = random.randint(16,30) if first_octet >=192 and first_octet <= 223: cidr_bits = random.randint(24,30) return cidr_bits