java ip 掩码计算cidr,从IP范围转换为CIDR掩码

博客探讨了将IPv4和IPv6地址范围转换为CIDR(无类别域间路由)表示法的最坏情况。作者提到,对于IPv4,最大可能的CIDR前缀数是62(32 * 2 - 2),而对于IPv6,这个数字是254(128 * 2 - 2)。文章提供了一个修改过的C语言实现,该实现不使用递归,用于进行这种转换,并给出了Python脚本的示例。
摘要由CSDN通过智能技术生成

I've been working on an algorithm for converting an IP Range to a list IPs in CIDR Notation (will be mentioned as tuples henceforth).

Now, what puzzles me is figuring out what is the Worst Case Scenario for this conversion;

What is the maximum number of tuples I can get for an IPv4 Range?

What is the maximum number of tuples I can get for an IPv6 Range?

How was this calculated?erp

I'm using a modified C version (which is not recursive) 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)

解决方案

It is just guess, but seems to be, that maximum number for CIDR prefixes in single IPv4 range is 62 (32*2 - 2), and for IPv6 - 254 (128*2 - 2).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值