当我们有 4 个八位字节
格式的 start_ip 并且步骤也采用 4 个八位字节格式时,如何在 python 中增加 IP 地址。
假设我从 IP 地址 225.1.1.1
开始,步骤为 0.0.0.1
当我说 next_ip = start_ip + step 时,它实际上应该评估扩展产生的结果。
我知道 ipaddr 模块只需添加一个即可完成此操作,但当该步骤也以 ipv4 格式给出时,这似乎不起作用。
执行此操作的任何已知步骤:
import ipaddr
a = ipaddr.ipaddress('225.1.1.1')
b = a +1
这实际上返回了期望的结果。但是当像这样增加时:
b = a + 0.0.0.1 it does not seem to work.
有任何已知的解决方案吗?
最佳答案
未精炼,但我猜可以用,这是 python 片段
def increment_ip_addr(ip_addr):
ip_arr = ip_addr.split('.')
def increment_by_1(digit):
return str(int(digit) + 1)
if int(ip_arr[3]) > 254:
ip_arr[3] = "1"
if int(ip_arr[2]) > 254:
ip_arr[2] = "1"
if int(ip_arr[1]) > 254:
ip_arr[1] = "1"
if int(ip_arr[0]) > 254:
ip_arr[0] = "1"
else:
ip_arr[0] = increment_by_1(ip_arr[0])
else:
ip_arr[1] = increment_by_1(ip_arr[1])
else:
ip_arr[2] = increment_by_1(ip_arr[2])
else:
ip_arr[3] = increment_by_1(ip_arr[3])
print(f"for ip address: {ip_addr} The incremented ip is: {'.'.join(ip_arr)}")
[increment_ip_addr(ip_addr) for ip_addr in ['1.1.1.1', "1.1.1.255", "1.255.1.255", "255.255.255.255"]]
对应的控制台输出:
for ip address: 1.1.1.1 The incremented ip is: 1.1.1.2
for ip address: 1.1.1.255 The incremented ip is: 1.1.2.1
for ip address: 1.255.1.255 The incremented ip is: 1.255.2.1
for ip address: 255.255.255.255 The incremented ip is: 1.1.1.1
如果有优化版本请告诉我
关于python - 当在Python中的步骤中给出IP地址时增加IP地址,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59801524/