合并网段算法
2010-08-21 20:09 Logic0 阅读(1564) 评论(0) 编辑 收藏 举报给定IP地址和子网掩码,进行网段合并。
python代码:
import sys
import os
from collections import defaultdict
ip_in = open("ip.txt","r")
maskip_map=defaultdict(set)
iplist=set()
for ipmask in [k for k in ip_in.readlines()]:
ip,mask=ipmask.split('/')
mask=32-int(mask)
ip=reduce(lambda a,b:(a<<8)+b,[int(i) for i in ip.split('.')])>>mask
iplist.add((mask,ip))
for mask,ip in sorted(iplist,reverse=True):
for i in sorted((k for k in maskip_map.iterkeys() if k>=mask)):
ip_set=maskip_map[i]
if i==mask:
if ip in ip_set:
break
if ip^1 in ip_set:
ip_set.remove(ip^1)
ip=ip/2
mask+=1
else:
if ip>>i-mask in ip_set:
break
else:
maskip_map[mask].add(ip)
for mask in maskip_map.iterkeys():
for ip in maskip_map[mask]:
ip=ip<<mask
first = int((ip >> 24) & 255)
second = int((ip >> 16) & 255)
third = int((ip >> 8) & 255)
fourth = int(ip & 255)
print '%d.%d.%d.%d/%d'% (first, second, third, fourth,32-mask)