In Java, given an IP Address range, return the minimum list of CIDR blocks that covers the range

后端 未结 5 1822
野趣味
野趣味 2021-01-03 02:04

I am having trouble with some of the logic in converting an IP Address range into a list of CIDR blocks. I do believe that this website is doing it right: http://ip2cidr.com

5条回答
  •  孤街浪徒
    2021-01-03 03:01

    The open-source IPAddress Java library can do this for you. Disclaimer: I am the project manager of the IPAddress library.

    Here is a sample method to do it:

    static void toPrefixBlocks(String str1, String str2) {
        IPAddressString string1 = new IPAddressString(str1);
        IPAddressString string2 = new IPAddressString(str2);
        IPAddress one = string1.getAddress(), two = string2.getAddress();
        IPAddressSeqRange range = one.toSequentialRange(two);
        System.out.println("starting with range " + range);
        IPAddress blocks[] = range.spanWithPrefixBlocks();
        System.out.println("prefix blocks are " + Arrays.asList(blocks));
    }
    

    Using your example:

    toPrefixBlocks("1.1.1.111","1.1.1.120");
    

    The output is:

    starting with range 1.1.1.111 -> 1.1.1.120
    prefix blocks are [1.1.1.111/32, 1.1.1.112/29, 1.1.1.120/32]
    

提交回复
热议问题