Search code examples
javaipcidr

How to convert IP address range to CIDR in Java?


I am trying to convert the IP address range into the CIDR notation in Java. Can someone provide an example of how this can be achieved?

I used the SubnetUtils for converting the CIDR to the IP address range, but I can't figure out the other way around.

For example: (using http://ip2cidr.com/)

Input 1: 5.10.64.0

Input 2: 5.10.127.255

Result: 5.10.64.0/18


Solution

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

    Here is sample code 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.spanWithRange(two);
        System.out.println("starting with range " + range);
        IPAddress blocks[] = range.spanWithPrefixBlocks();
        System.out.println("prefix blocks are " + Arrays.asList(blocks));
    }
    

    This is how you would use IPAddress to produce the range from the original CIDR string:

    static String[] toRange(String str) {
        IPAddressString string = new IPAddressString(str);
        IPAddress addr = string.getAddress();
        System.out.println("starting with CIDR " + addr);
        IPAddress lower = addr.getLower(), upper = addr.getUpper();
        System.out.println("range is " + lower + " to " + upper);
        return new String[] {lower.toString(), upper.toString()};
    }
    

    For your example, we run this code:

    String strs[] = toRange("5.10.64.0/18");
    System.out.println();
    toPrefixBlocks(strs[0], strs[1]);
    

    The output is:

    starting with CIDR 5.10.64.0/18
    range is 5.10.64.0/18 to 5.10.127.255/18
    
    starting with range 5.10.64.0 -> 5.10.127.255
    prefix blocks are [5.10.64.0/18]