我已编写代码来计算子网中的免费IP。代码如下,
现在有一个条件,一旦我们找到子网中的第一个免费IP,就需要在同一个子网中有一些连续数量的IP应该是空闲的(缓冲区IP)。一旦条件满足,代码应返回第一个免费IP。
鉴于代码工作正常,但我遇到问题,我需要在同一子网中搜索多个免费IP并尊重上述条件。在这种情况下,在第一次迭代中,我能够找到自由IP,在第二次迭代中,我想我们应该添加缓冲区IP并开始搜索,但不知道如何实现它。
任何帮助将不胜感激。
def ip_definer(start, end, cidr, ip_buffer):
start_ip = ipaddress.ip_address(start) #DHCP Allocation Pool Start IP
end_ip = ipaddress.ip_address(end) #DHCP Allocation Pool End IP
net_cidr = ipaddress.IPv4Network(cidr) #Network CIDR
used_ports = []
free_ip = []
lap = []
for ip_pool in net_cidr:
if (ip_pool >= start_ip) and (ip_pool <= end_ip): ##Makind sure that we iterate withing the DHCP Allocation Pool Start and End IP Range
scale_ip = port_crawler(ip_pool, ip_buffer, used_ports, free_ip, lap, end)
def port_crawler(ip_pool, ip_buffer, used_ports, free_ip, lap, end):
if str(ip_pool) in used_ports: #### Looking for Free IP, Wher 'used_ports' is a list of occupied IPs.
print "IP {0} is used".format(ip_pool)
else:
n = len(free_ip)
if n == 0:
free_ip.append(ip_pool) ### First Free IP in the Subnet
if end == str(ip_pool): ### If we hit the Last IP of subnet.
lap.append(free_ip[-1]) ## Store Last IP of the 'Last free IP' found in Previous iteration.
if (n > 0) and (n < ip_buffer): ### Checking for IP buffer (addition consecutive free IPs)
index = n - 1
if ip_pool == free_ip[index] + 1:
free_ip.append(ip_pool)
else:
del free_ip[0:len(free_ip)]
if (len(free_ip) == ip_buffer): ### if length of IP buffer is equal to length to lenght of free_ips, return first Free IP
scale_ip = str(free_ip[0])
return scale_ip
另外,为了解释一下,下面的代码片段在第一次迭代中起作用,其中一圈内容将填充“最后一个免费IP”。在下一次迭代中,代码应该开始寻找来自“最后一个免费IP”+“缓冲区IP”+ 1的免费IP,这是不可行的感染我无法理解我应该如何实现。
if end == str(ip_pool):
lap.append(free_ip[-1])