我必须在特定网络中选择三个随机子网。网络本身将始终具有/ 24子网掩码(我总是使用10.10.127.0进行测试)。这些随机子网可以具有/ 25子网掩码,一直到/ 29。现在最棘手的问题是子网的重叠。您在下面看到的代码看起来可能写得不好,但它可以完成工作。
但是只有一个例外:当选择前两个非重叠子网时,其中一个在10.10.127.0/25范围内,另一个在10.10.127.128/25范围内,我得到一个无限的每当被选择的第三个子网具有/ 25子网掩码时循环。这当然是有道理的,以前选择的两个子网都已经在/ 25个子网范围内。
我的问题是:我如何解决这个问题并改进代码?如前所述,代码看起来写得不好,但是我不是一个优秀的程序员,我仍然尽可能多地学习以提高我的技能。
import random
from netaddr import *
import itertools
def getRandomIP(networkIp=raw_input("Enter the desired network: ")):
chosenSubnets = []
network = networkIp + '/24'
ip = IPNetwork(network)
print ip
def subnetOverlap(randomSubnet1, randomSubnet2):
return (randomSubnet1.first <= randomSubnet2.last and
randomSubnet2.first <= randomSubnet1.last)
for randomNumber in random.sample(range(25, 30), 3):
subnetList = list(ip.subnet(randomNumber))
restartLoop = True
while restartLoop:
restartLoop = False
for subnet in random.sample(subnetList, 1):
chosenSubnets.append(subnet)
for pair in itertools.combinations(chosenSubnets , 2):
if subnetOverlap(IPNetwork(pair[0]),
IPNetwork(pair[1])) == True:
print 'OVERLAP'
chosenSubnets.pop()
restartLoop = True
print chosenSubnets
break
print subnet
getRandomIP()
答案 0 :(得分:1)
我试图模仿我认为是你原来的意图。具体来说,我
具体而言,可以突出显示代码中的一些更改:
希望有所帮助。
import random
from netaddr import *
import itertools
def subnetOverlap(randomSubnet1, randomSubnet2):
return (randomSubnet1.first <= randomSubnet2.last and
randomSubnet2.first <= randomSubnet1.last)
def getRandomIP(networkIp="10.10.127.240"):
network = networkIp + '/24'
ip = IPNetwork(network)
print ip
while 1:
chosenSubnets = []
overlap = False
#Choose 3 random subnetLists
for randomNumber in random.sample(range(25,30),3):
subnetList = list(ip.subnet(randomNumber))
#For each subnetList choose a subnet
chosenSubnets.append(random.sample(subnetList,1)[0])
#Check whether any pairs overlap
for pair in itertools.combinations(chosenSubnets,2):
if subnetOverlap(pair[0],pair[1]):
print "OVERLAP"
overlap = True
break
#No overlaps found
if overlap==True: continue
if overlap==False: break
#print chosenSubnets
return chosenSubnets
#networkIp = raw_input("Enter the desired network: ")
for i in range(20):
print "***************************"
print getRandomIP("10.10.127.240")
#getRandomIP(networkIp)