我试图获取一个包含IP地址‘带有子网掩码的列表(1.0.0.0/24),并计算该列表中IP地址的总数。然而,我试图避免计算相同的IP地址‘,但有一个更高的子网掩码。
例1.0.0.0/24 1.0.0.0/16 1.0.0.0/8
这里我只想使用/8来计算IP地址,因为is包含/16和/24
我把所有的IP地址都放进了一个列表,newSet,就像.
例1.0.0.0/24 1.0.0.0/16 1.0.0.0/8 2.0.0.0/24 2.0.0.0/16等等
然后使用以下代码弹出子网掩码/24、/16、/8等.就像这样
subIP = [i.split('/', 1)[1] for i in newSet]然后计算ipTotal的IP空间是全局声明的。
for element in subIP:
y = 32 - int(element)
x = pow(2, y)
ipTotal = ipTotal + x 但是,当我只需要计算1.0.0.0/8时,我现在正在计算1.0.0.0/24、1.0.0.0/16和1.0.0.0/8。
基本上,我已经计算过IP空间的数量了。
我需要怎么处理这件事?我想把1.0.0.0放到一个列表中,然后把/24放到另一个列表中.然后运行一个嵌套的for循环来进行比较,但我非常肯定这是行不通的。
发布于 2014-07-31 22:59:52
ip_dict = {}
for ip_subnet in newSet:
ip,subnet = ip_subnet.split('/')
subnet = int(subnet)
if ip not in ip_dict or ip_dict[ip] > subnet:
ip_dict[ip] = subnet
updated_list = [str(ip)+"/"+str(subnet) for ip,subnet in ip_dict.iteritems()]
ipTotal = 0
for subnet in ip_dict.values():
y = 32 - int(subnet)
x = pow(2, y)
ipTotal = ipTotal + x 您可以使用一个非常适合惟一key,value配对的字典,只需做您想要的检查,然后表单将地址重新构成一个列表。
updated_list将是具有该IP最小子网的唯一IP地址的列表。
ip_dict.values()给出了这些唯一IP的子网列表。
发布于 2014-07-31 23:09:37
您应该将ip /子网的列表解析为dict,其中ip为键,一组子网为值。然后,您将遍历这些键,在子网集上找到最小值,并将您的计算仅应用于该ip/子网。
就像这样:
import collections
ip_subnet_list=['1.0.0.0/31', '1.0.0.0/30', '5.0.0.0/22']
data = collections.defaultdict(set)
for item in ip_subnet_list:
ip, subnet = item.split('/')
data[ip].add(int(subnet))
ip_count = 0
for ip, subnets in data.iteritems():
subnet = min(subnets)
ip_count += pow(2, 32 - subnet)
print ip_counthttps://stackoverflow.com/questions/25070202
复制相似问题