gpt4 book ai didi

从 IP 范围到 CIDR 掩码的转换

转载 作者:太空宇宙 更新时间:2023-11-04 00:09:10 26 4
gpt4 key购买 nike

我一直在研究一种算法,用于将 IP 范围转换为 CIDR 表示法中的 IP 列表(此后将作为元组提及)。现在,让我感到困惑的是弄清楚这种转换的最坏情况是什么;

对于 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)

最佳答案

这只是猜测,但似乎是,单个 IPv4 范围内 CIDR 前缀的最大数量为 62 (32*2 - 2),对于 IPv6 - 254 (128*2 - 2)。

关于从 IP 范围到 CIDR 掩码的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10228219/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com