簡體   English   中英

改進隨機選擇:Python 子網掩碼生成器

[英]Improving random selection: Python subnet mask generator

我創建了這段代碼來隨機生成一個隨機子網掩碼(所以我可以在紙上練習將它們轉換為相關的前綴)。 我一次隨機創建一個八位字節的子網掩碼,但如果任何八位字節不是 255,則 rest 自動為“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())

結果,我的大多數 output 都沒有超過第一個或第二個八位字節。 例如:128.0.0.0、192.0.0.0、254.0.0.0 等。不時我會得到類似:255.255.192.0

我認為這是一個學習在代碼中使用隨機性的有趣機會。

任何人都可以推薦一種使此代碼對其他子網掩碼可能性更公平的方法嗎? 我意識到我還可以列出所有子網掩碼並隨機選擇列表中的元素。

提前謝謝你,塞巴斯蒂安

這是我為測試子網掩碼驗證器所做的修改版本:

注意- 在 Rocky Linux 8.6(綠色黑曜石)中使用 Python 2.7 進行測試

from random import randint

subnet_mask_list = []
prefix = 32
octets = (0, 128, 192, 224, 240, 248, 252, 254, 255,)
a = b = c = d = len(octets) - 1
# Create a list of dictionary items, consisting of a prefix (key) and mask (val),
# in descending order
while a > 0:
    # Add an item first...
    mask = '{0}.{1}.{2}.{3}'.format(octets[a], octets[b], octets[c], octets[d])
    subnet_mask_list.append({'prefix': prefix, 'mask': mask})
    # Then decrement the prefix and the subnet...
    prefix -= 1
    a -= 1 if b == 0 else 0
    b -= 1 if c == 0 and b > 0 else 0
    c -= 1 if d == 0 and c > 0 else 0
    d -= 1 if d > 0 else 0

# Iterate and query
for _ in range(100):
    r = randint(0, len(subnet_mask_list) - 1)
    try:
        p = input(
            'What is the prefix of {0} (Enter 0 to quit): '.format(
                subnet_mask_list[r]['mask']))
        if p == 0:
            print('Good-bye!')
            break
        elif p == subnet_mask_list[r]['prefix']:
            print('Good to go!')
        else:
            print('Nope.')
    except (NameError, SyntaxError):
        # Catch invalid entries here
        print('Nope.')

Output:

What is the prefix of 255.0.0.0 (Enter 0 to quit): 8
Good to go!
What is the prefix of 255.255.255.255 (Enter 0 to quit): 32
Good to go!
What is the prefix of 248.0.0.0 (Enter 0 to quit): 100
Nope.
What is the prefix of 255.255.248.0 (Enter 0 to quit): 21
Good to go!
What is the prefix of 255.224.0.0 (Enter 0 to quit): qwerty
Nope.
What is the prefix of 255.255.255.192 (Enter 0 to quit): 0
Good-bye!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM