Python 如何从CIDR地址生成IP地址
在本文中,我们将学习如何从CIDR地址生成IP地址。
使用的方法,以下是完成此任务的各种方法:
- 生成IPv4网络地址
- 生成IPv6网络地址
- 访问CIDR地址的IP地址
方法1:IPv4Network
步骤
执行所需任务的算法/步骤如下:
- 使用import关键字导入ipaddress模块。
- 使用ipaddress模块的ip_network()函数(返回地址的网络类型)获取来自输入的CIDR地址(IPv4Network)的IP地址。
- 使用for循环遍历上述IPv4地址列表。
- 打印当前列表的IPv4地址。
示例
以下程序返回给定CIDR地址的IPv4地址列表:
# importing ipaddress module
import ipaddress
# getting the IP addresses from an input CIDR address(IPv4 network address)
netIpv4Address = ipaddress.ip_network('123.45.66.64/27')
print("The Following are the IPv4 Addresses in the given CIDR Address(123.45.66.64/27)")
# traversing through the above IPv4 addresses list
for i in netIpv4Address:
# printing the current IPv4 address
print(i)
输出
在执行时,上述程序将生成以下输出:
The Following are the IPv4 Addresses in the given CIDR Address(123.45.66.64/27)
123.45.66.64
123.45.66.65
123.45.66.66
123.45.66.67
123.45.66.68
123.45.66.69
123.45.66.70
123.45.66.71
123.45.66.72
123.45.66.73
123.45.66.74
123.45.66.75
123.45.66.76
123.45.66.77
123.45.66.78
123.45.66.79
123.45.66.80
123.45.66.81
123.45.66.82
123.45.66.83
123.45.66.84
123.45.66.85
123.45.66.86
123.45.66.87
123.45.66.88
123.45.66.89
123.45.66.90
123.45.66.91
123.45.66.92
123.45.66.93
123.45.66.94
123.45.66.95
方法2:IPv6网络
将IPv6网络的CIDR地址作为参数传递给ip_network()函数,并通过遍历结果打印出所有IPv6网络。
示例
以下程序返回给定CIDR地址的IPv6地址列表。
# importing ipaddress module
import ipaddress
# getting the IP addresses from an input CIDR address(IPv6 network address)
netIpv6Address = ipaddress.ip_network('12:3456:78:90ab:cd:ef11:23:30/125')
print("The Following are the IPv6 Addresses in the given CIDR Address(12:3456:78:90ab:cd:ef11:23:30/125)")
# traversing in the above Ipv6Address
for i in netIpv6Address:
# printing the current Ipv6Address
print(i)
输出
在执行后,上述程序将生成如下输出结果 –
The Following are the IPv6 Addresses in the given CIDR Address(12:3456:78:90ab:cd:ef11:23:30/125)
12:3456:78:90ab:cd:ef11:23:30
12:3456:78:90ab:cd:ef11:23:31
12:3456:78:90ab:cd:ef11:23:32
12:3456:78:90ab:cd:ef11:23:33
12:3456:78:90ab:cd:ef11:23:34
12:3456:78:90ab:cd:ef11:23:35
12:3456:78:90ab:cd:ef11:23:36
12:3456:78:90ab:cd:ef11:23:37
方法3:访问CIDR地址的IP地址
我们可以通过将给定的CIDR地址作为列表获取所有与之对应的IP地址,并使用[]操作符即索引方法访问列表元素来访问它们。
示例
以下程序展示了如何访问CIDR地址的IP地址 –
# importing ipaddress module
import ipaddress
# getting the IP addresses from an input CIDR address(IPv4 network address)
netIpv4Address = ipaddress.ip_network('123.45.66.64/27')
# accessing the first Ipv4Address from the resultant list
print("First Ipv4Address from the list:", netIpv4Address[0])
# accessing the second Ipv4Address from the resultant list
print("Second Ipv4Address from the list:", netIpv4Address[1])
# accessing the last Ipv4Address from the resultant list
print("Last Ipv4Address from the list:", netIpv4Address[-1])
输出
在执行上述程序后,将生成以下输出结果:
First Ipv4Address from the list: 123.45.66.64
Second Ipv4Address from the list: 123.45.66.65
Last Ipv4Address from the list: 123.45.66.95
结论
本文教我们如何从提供的CIDR地址中提取每个IP地址。我们使用了两种方法,一种是获取所有IPv4地址,另一种是收集IPv6地址。我们还展示了如何使用[]运算符在将IP地址转换为列表后访问它们。