lundi 27 janvier 2020

Improving random selection: Python subnet mask generator

I created this code to generate random a random subnet mask (so I could practice converting them to their associated prefix, on paper). I am randomly creating a subnet mask one octet at a time, but if any octet is NOT 255, the rest are automatically "0":

from random import randint

# choose subnet bytes at random
def pick_num():
    # list of valid subnet bytes
    list = [0, 128, 192, 224, 240, 248, 252, 254, 255]

    random = randint(0,8)
    num = list[random]
    return num

def generate_netmask():
    current_byte = 0
    submask_mask = ""
    count = 1
    while count <= 4:
        current_byte = pick_num()
        if current_byte == 255:
            submask_mask += str(current_byte) + "."
            count += 1
        else:
            submask_mask += str(current_byte) + "."
            count += 1
            break

    while count != 5:
        if count != 4:
            submask_mask += "0."
            count += 1
        elif count == 4:
            submask_mask += "0"
            count += 1

    return submask_mask

print(generate_netmask())

As a result, a majority of my output doesn't make it past the 1st or 2nd octet. For example: 128.0.0.0, 192.0.0.0, 254.0.0.0, etc. Every now and then I'll get something like: 255.255.192.0

I'm seeing this as a fun opportunity to learn about using randomness in code.

Can anyone recommend a way/ways of making this code more fair to the other subnet masks possibilities? I realize I could also make a list of all the subnet masks and randomly choose elements in the list.

Thank you in advance, Sebastian




Aucun commentaire:

Enregistrer un commentaire