Python使用ipaddress模块确定给定的IPv4地址是否为保留地址

Python使用ipaddress模块确定给定的IPv4地址是否为保留地址

在传统的IPv4寻址方案中,IP地址被划分为五类:A、B、C、D和E。E类地址范围在240.0.0.0到255.255.255.255之间,被指定为特定目的使用,不适用于当前互联网基础设施的普遍使用。因此,E类地址被视为“保留地址”,不在公共互联网上分配或路由。

为了确定给定的IPv4地址是否落在由互联网工程任务组(IETF)和互联网号分配机构(IANA)等组织定义的保留IP地址范围内,Python利用了ipaddress模块提供的IPv4Address对象的is_reserved属性。通过检查这个属性,我们可以准确地确定给定的地址是否为保留地址。

输入输出场景

让我们看一些使用ipaddress模块确定给定的IPv4地址是否为保留地址的Python程序的输入输出场景:

场景1:

Input: "192.168.0.1"
Output: The address 192.168.0.1 is not reserved.

情景2−

Input: "10.0.0.1"
Output: The address 10.0.0.1 is reserved.

场景3 –

Input: "172.16.0.1"
Output: The address 172.16.0.1 is not reserved.

情景4 –

Input: "240.10.0.1"
Output: The address 240.10.0.1 is reserved.

方法

我们可以按照以下步骤使用Python中的ipaddress模块确定给定的IPv4地址是否保留。

  • 导入ipaddress模块。

  • 定义一个包含一些示例IPv4地址的列表。

  • 遍历列表中的每个IPv4地址,并使用ip_address()方法创建一个IPv4Address对象。

  • 最后,使用IPv4Address对象的is_reserved属性确定地址是否保留。

ipaddress.ip_address()方法

用于创建表示IP地址的IPv4Address或IPv6Address对象。该方法根据提供的地址类型返回IPv4Address或IPv6Address对象。如果输入地址无效,例如格式不正确或超出范围的值,则会引发ValueError。ip_address()方法的语法如下:

ipaddress.ip_address(address)

其中,address参数是我们要创建对象的IP地址的字符串表示形式。

is_reserved属性

它是ipaddress模块中IPv4Address对象的属性。它用于根据IETF和IANA等各种组织定义的保留IP地址范围来确定IP地址是否保留。

如果IP地址为保留地址,则返回True,否则返回False。

示例

让我们举个例子,看看如何使用Python中的ipaddress模块来确定给定的IPv4地址是否保留。

import ipaddress

# define a list of ipv4 addresses 
ipv4_addresses = [
    "240.10.0.1",
    "10.0.0.1",   
    "172.16.0.1", 
    "192.168.0.1",
    "241.0.0.133",
]

# Check if each IPv4 address is reserved or not
for address in ipv4_addresses:
    ip = ipaddress.ip_address(address)
    if ip.is_reserved:
        print("The address {} is reserved.".format(address))
    else:
        print("The address {} is not reserved.".format(address))

输出

The address 240.10.0.1 is reserved.
The address 10.0.0.1 is not reserved.
The address 172.16.0.1 is not reserved.
The address 192.168.0.1 is not reserved.
The address 241.0.0.133 is reserved.

示例

在此示例中,我们将使用try-except块来处理任何无效的地址输入。

import ipaddress

# define a list of ipv4 addresses 
ipv4_addresses = [
    "240.10.0.1",
    "10.0.0.1",   
    "172.16.0.1", 
    "192.168.0.1",
    "241.0.0.133",
    "0.3.12"
]

# Check if each IPv4 address is reserved or not
for address in ipv4_addresses:
    try:
        ip = ipaddress.ip_address(address)
        if ip.is_reserved:
            print("The address {} is reserved.".format(address))
        else:
            print("The address {} is not reserved.".format(address))
    except ValueError:
        print("The address {} is not a valid IPv4 address.".format(address))

输出

The address 240.10.0.1 is reserved.
The address 10.0.0.1 is not reserved.
The address 172.16.0.1 is not reserved.
The address 192.168.0.1 is not reserved.
The address 241.0.0.133 is reserved.
The address 0.3.12 is not a valid IPv4 address.

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程