为什么这段代码在某些情况下不能识别IP的class?

Why this code does not identify the class of an IP in some cases?

我编写了以下 Python 代码,用于 class 验证 IP 是否有效,如果有效则 class 它属于什么以及它是否是私有的:

from ipaddress import IPv4Address, IPv4Network, ip_address
import sys

try:
    ip = ip_address(sys.argv[1])
    print(f"{ip} is a correct IP{ip.version} address.")
    if ip_address(ip).is_private:
            print("It is a private IP.")
    classA = IPv4Network(("10.0.0.0", "255.0.0.0")) 
    classB = IPv4Network(("172.16.0.0", "255.240.0.0"))
    classC = IPv4Network(("192.168.0.0", "255.255.0.0")) 
    if ip in classA:
        print(f"{ip} is a correct class A IP{ip.version} address.")
        if ip_address(ip).is_private:
            print("It is a private IP.")
    elif ip in classB:
        print(f"{ip} is a correct class B IP{ip.version} address.")
        if ip_address(ip).is_private:
            print("It is a private IP.")
    elif ip in classC:
        print(f"{ip} is a correct class C IP{ip.version} address.") 
        if ip_address(ip).is_private:
            print("It is a private IP.")
except ValueError:
    print(f'address/netmask is invalid: {sys.argv[1]}')
except:
    print(f'Usage : {sys.argv[0]}  ip')

我假设 that the range of class A 是从 1.0.0.0127.255.255.255,class B 是从 128.0.0.0191.255.255.255,而class的C是从192.0.0.0223.255.255.255。 当给出 141.68.27.102 时,它不会 class将 class 定义为 B(尽管 the answer to this cisco lab does),为什么会这样? 当给出 192.12.13.14 时,它不会 class将 class 定义为 C(尽管 the answer to this cisco lab does),为什么这样?

简短的回答是“因为这些 IP 不属于您定义的 classes”。

您的程序的这种稍微简化的返工首先打印出 classes,因此您可以看到您是如何定义它们的……以及为什么它们似乎没有正确匹配。

from ipaddress import IPv4Network, ip_address

classes = {
    "A": IPv4Network(("10.0.0.0", "255.0.0.0")),
    "B": IPv4Network(("172.16.0.0", "255.240.0.0")),
    "C": IPv4Network(("192.168.0.0", "255.255.0.0")),
}


def describe_ip(ip_str):
    ip = ip_address(ip_str)
    for class_name, network in classes.items():
        if ip in network:
            print(f"{ip} is a correct class {class_name} IP{ip.version} address.")
            break
    else:
        print(f"{ip} does not belong in any of the classes defined.")


print(classes)
describe_ip("172.32.255.255")
describe_ip("141.68.27.102")
describe_ip("192.12.13.14")
describe_ip("172.16.255.255")

输出类似于(最后一行证明 172.16. 地址确实符合您的 B class 定义)。

{'A': IPv4Network('10.0.0.0/8'), 'B': IPv4Network('172.16.0.0/12'), 'C': IPv4Network('192.168.0.0/16')}
172.32.255.255 does not belong in any of the classes defined.
141.68.27.102 does not belong in any of the classes defined.
192.12.13.14 does not belong in any of the classes defined.
172.16.255.255 is a correct class B IP4 address.