![](/img/trans.png)
[英]How to efficiently check if a given IP Address belong to an IP subnetwork in Python?
[英]Increment an IP address when the IP address is given in steps in python
当我们有4 octets
格式的 start_ip 和4 octets
格式的步骤时,如何在 python 中增加 IP 地址。
假设我从 IP 地址225.1.1.1
,步长为0.0.0.1
当我说 next_ip = start_ip + step 时,它实际上应该评估 expand 产生的结果。 我知道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.
任何已知的解决方案?
这段代码可以添加两个 4 个八位字节:
first = '192.168.0.4'
second = '0.0.0.1'
ipaddress.ip_address(first) + int(ipaddress.ip_address(second))
这将导致: IPv4Address('192.168.0.5')
没有精炼,但我猜是有效的,这里是 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
如果有优化版本,请告诉我
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.