-1

我第一次来这里,有一个问题请教:

我想检查用户在输入 ipv4 时是否输入如果不是 ipv4 用户应该收到 3 次错误然后退出。我的示例代码如下:

    # Hosts and Commands
    for attempt in range(3):
        host = input("Enter IPs separated by SPACE: ")
        cmd = input("Enter Command(s) seperated by ',' : ")
        if(len(host) != 0) and (len(cmd) != 0):
            break
        print("Fields Cannot be Blank, try again...")
    else:
        Screen().input("Sorry...Execution Terminated, Press [ENTER] to Exit")
        return
4

2 回答 2

0
def validateIP(s):
    if not s: return False
    try:
        parts = [int(p) for p in s.split('.')]
    except:
        return False

    if len(parts) != 4: return False
    for part in parts:
        if not(0 <= part <= 255):
            return False
    return True


max_attempts = 3
for remaining in range(max_attempts-1, -1, -1):
    ip = input("Enter an IPv4 address: ")
    if validateIP(ip.strip()): break
    print("That is an invalid IPv4 address. You have", remaining, "attempts left")
于 2020-06-01T06:31:13.123 回答
-1

谢谢inspectorG4dget!如果我在数组中只添加一个 IP,它工作正常,如果我键入超过 1 个以空格分隔,稍后在数组中捕获它不起作用。这个想法是接收用户希望咨询的尽可能多的 ip,但用户不能键入无效的 ipv4。

于 2020-06-03T03:21:15.370 回答