-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathprefixCutter.py
229 lines (204 loc) · 7.46 KB
/
prefixCutter.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
__author__ = 'baohua'
import math
class Cutter():
"""
The Convertor class.
>>> t=Cutter(0,1)
>>> t=Cutter(0,-1)
Invalid input! min=0, max=-1
>>> t=Cutter(-1,1)
Invalid input! min=-1, max=1
"""
def __init__(self, min=0,max=0):
if min > max or min<0 or max<0:
print "Invalid input! min=%d, max=%d" %(min,max)
else:
self.min,max = min,max
def genCuttedPrefix(self,prefixes):
"""
Given two prefixes, calculate the resulted cutted prefixes
>>> Cutter().genCuttedPrefix(['10.0.0.0/8','10.1.0.0/24'])
['10.0.0.0/16', '10.1.0.0/24', '10.1.1.0/24', '10.1.2.0/23', '10.1.4.0/22', '10.1.8.0/21', '10.1.16.0/20', '10.1.32.0/19', '10.1.64.0/18', '10.1.128.0/17', '10.2.0.0/15', '10.4.0.0/14', '10.8.0.0/13', '10.16.0.0/12', '10.32.0.0/11', '10.64.0.0/10', '10.128.0.0/9']
"""
range_list=self.cutPrefixToRange(prefixes)
result=[]
if range_list:
for range in range_list:
result.extend(self.getPrefixFromRange(range[0],range[1]))
return result
def cutPrefixToRange(self,prefixes):
"""
Given two prefixes, calculate the range cutted
>>> Cutter().cutPrefixToRange(['10.0.0.0/8','10.1.0.0/24'])
[(167772160, 167837695), (167837696, 167837951), (167837952, 184549375)]
"""
if len(prefixes)!=2:
print "pls check the input prefixes number ",len(prefixes)
return None
result=[]
ip,ip_start,ip_end,mask,mask_len=['',''],[0,0],[0,0],[0,0],[0,0]
for i in range(len(prefixes)):
ip[i],mask_len[i] = prefixes[i].split('/')
ip[i],mask_len[i] = self.ipToInt(ip[i]),int(mask_len[i])
if mask_len[i]!=32:
mask[i] = (1<<(32-mask_len[i]))-1
ip_start[i]=ip[i]&(~mask[i])
ip_end[i]=ip[i]|mask[i]
else:
ip_start[i],ip_end[i]=ip[i],ip[i]
#print self.intToIP(ip_start[i]),self.intToIP(ip_end[i])
if ip_start[0]>ip_start[1]:
ip_start[0],ip_start[1] = ip_start[1],ip_start[0]
ip_end[0],ip_end[1] = ip_end[1],ip_end[0]
if ip_end[0]<ip_start[1]:
result.append((ip_start[0],ip_end[0]))
result.append((ip_start[1],ip_end[1]))
else:
if(ip_start[1]>ip_start[0]):
result.append((ip_start[0],ip_start[1]-1))
result.append((ip_start[1],min(ip_end[0],ip_end[1])))
if(ip_end[0]!=ip_end[1]):
result.append((min(ip_end[0],ip_end[1])+1,max(ip_end[0],ip_end[1])))
return result
def ipToInt(self,ip):
"""
Calculate the ip format string into number.
>>> Cutter().ipToInt('10.0.0.2')
167772162
"""
ipseg = ip.split('.')
assert len(ipseg)==4
result=0
for i in range(len(ipseg)):
result<<=8
result+=int(ipseg[i])
return result
def intToIP(self,value):
"""
Calculate the ip format string with given number.
>>> Cutter().intToIP(10*16777216+2)
'10.0.0.2'
"""
ip=[]
for i in range(4):
ip.insert(0,str(value&0xff))
value>>=8
return '.'.join(ip)
def getPrefixFromRange(self,min,max):
"""
Get prefixes that can represent the given range.
>>> t= Cutter()
>>> t.getPrefixFromRange(0,1)
['0.0.0.0/32', '0.0.0.1/32']
>>> t.getPrefixFromRange(0,7)
['0.0.0.0/29']
>>> t.getPrefixFromRange(1,6)
['0.0.0.1/32', '0.0.0.2/32', '0.0.0.3/32', '0.0.0.4/32', '0.0.0.5/32', '0.0.0.6/32']
>>> t.getPrefixFromRange(1,30)
['0.0.0.1/32', '0.0.0.2/32', '0.0.0.3/32', '0.0.0.4/30', '0.0.0.8/29', '0.0.0.16/29', '0.0.0.24/30', '0.0.0.28/32', '0.0.0.29/32', '0.0.0.30/32']
"""
if min>max:
return
result_range,result_prefix=[],[]
self.getPrefixFromRangeRun(min,max,result_range)
for range in result_range:
if range[1]-range[0]==1: #netmask = /31 is special case here
result_prefix.append(self.getPrefixString((range[0],range[0])))
result_prefix.append(self.getPrefixString((range[1],range[1])))
else:
result_prefix.append(self.getPrefixString(range))
return result_prefix
def getPrefixString(self,prefix_range):
"""
Convert a prefixable range into a prefix string.
"""
min,max=prefix_range[0],prefix_range[1]
assert self.isPrefixable(min,max)
mask=min^max
mask_len = 32-int(math.log(mask+1,2))
return str(self.intToIP(min))+'/'+str(mask_len)
def getPrefixFromRangeRun(self,min,max,result):
"""
Recursive function to cut the given range into prefixable ranges,
and store them into result.
"""
if min==max:
result.append((min,min))
return
if min&0x1:
tryMax=min
elif min==0: #margin is due to max
tryMax = 2**(int(math.log(max+1, 2)))-1
else: #margin is due to min
len_min=self.getZeroSuffixLen(min)
i = len_min
tryMax = min|((1<<i) -1)
while tryMax>max:
tryMax = min|((1<<i) -1)
i -= 1
result.append((min,tryMax))
if tryMax<max:
self.getPrefixFromRangeRun(tryMax+1,max,result)
def isPrefixable(self,min,max):
"""
Test if a given range can be converted into a prefix.
>>> Cutter().isPrefixable(0,1)
True
>>> Cutter().isPrefixable(1,2)
False
>>> Cutter().isPrefixable(4,5)
True
>>> Cutter().isPrefixable(0,2)
False
>>> Cutter().isPrefixable(8,11)
True
"""
if min<0 or max<min:
return False
if min==0 and self.getZeroSuffixLen(max-min+1)>0 or min==max:
return True
len_min = self.getZeroSuffixLen(min)
len_differ = self.getZeroSuffixLen(max-min+1)
return len_min >= len_differ and len_differ>0
def isPowerofTwo(self,num):
"""
Test if the given number is the power of 2
>>> Cutter().isPowerofTwo(-1)
False
>>> Cutter().isPowerofTwo(0)
False
>>> Cutter().isPowerofTwo(1)
True
>>> Cutter().isPowerofTwo(2)
True
>>> Cutter().isPowerofTwo(3)
False
"""
return num > 0 and (not(num & (num - 1)))
def getZeroSuffixLen(self,num):
"""
Get the '0' suffix string
>>> Cutter().getZeroSuffixLen(0)
1
>>> Cutter().getZeroSuffixLen(1)
0
>>> Cutter().getZeroSuffixLen(4)
2
"""
tmp= num
if tmp==0:
return 1
len=0
for i in range(32):
if tmp==0 or tmp&0x1: #last bit is 1 or the number is 0 already
break
else:
len+=1
tmp>>=1
return len
if __name__ == '__main__':
import doctest
doctest.testmod()
c= Cutter()
print len(c.genCuttedPrefix(['10.0.0.0/8','10.0.0.1/32']))
print c.genCuttedPrefix(['10.0.0.0/8','10.0.0.1/32'])