2
我一直在研究用於將IP範圍轉換爲CIDR表示法中的列表IP的算法(以後將作爲元組提及)。 現在,讓我感到困惑的是弄清楚這種轉換的最糟情況場景是什麼;從IP範圍到CIDR掩碼的轉換
什麼是我可以獲得IPv4範圍的元組的最大數量? 我可以獲得IPv6範圍的元組的最大數量是多少? 這是如何計算的ERP
我使用的是修改後C版(不遞歸)of the following Python script:
1 #!/usr/bin/env python
2
3 import sys
4 import re
5
6 def ip2int(ip) :
7 ret = 0
8 match = re.match("(\d*)\.(\d*)\.(\d*)\.(\d*)", ip)
9 if not match : return 0
10 for i in xrange(4) : ret = (ret << 8) + int(match.groups()[i])
11 return ret
12
13 def int2ip(ipnum) :
14 ip1 = ipnum >> 24
15 ip2 = ipnum >> 16 & 0xFF
16 ip3 = ipnum >> 8 & 0xFF
17 ip4 = ipnum & 0xFF
18 return "%d.%d.%d.%d" % (ip1, ip2, ip3, ip4)
19
20 def printrange(startip, endip) :
21 bits = 1
22 mask = 1
23 while bits < 32 :
24 newip = startip | mask
25 if (newip>endip) or (((startip>>bits) << bits) != startip) :
26 bits = bits - 1
27 mask = mask >> 1
28 break
29 bits = bits + 1
30 mask = (mask<<1) + 1
31 newip = startip | mask
32 bits = 32 - bits
33 print "%s/%d" % (int2ip(startip), bits)
34 if newip < endip :
35 printrange(newip + 1, endip)
36
37 while 1 :
38 line = sys.stdin.readline().strip()
39 if not line : break
40 chars = line.split(" ")
41 print "#%s - %s" % (chars[0], chars[1])
42 ip1 = ip2int(chars[0])
43 ip2 = ip2int(chars[1])
44 printrange(ip1, ip2)
對於C,有比Python更高效的算法,因爲在C中我們有[ffs和fls](http://en.wikipedia.org/wiki/Find_first_set)函數,作爲單個CPU指令執行。示例[用於IPv4](https://gist.github.com/4202877)。 – citrin 2012-12-04 11:34:16