Take the 2-minute tour ×

I have an ip array like below and I want to convert it to smallest cidr subnet list. Is there a library for that in Java?

For example:

converted to

Thanks in advance.

share|improve this question

2 Answers 2

up vote 1 down vote accepted

I don't know whether there is a library available in Java. Indeed, I know little about Java :) But I can give you an algorithm for solving the problem, if that is any help.

1) Convert the ip addresses into pairs of integers, where the first integer is the binary representation of the ip address (a.b.c.d -> a << 24 + b << 16 + c << 8 + d) and the second integer is 32 (that is, initially each address is it's own subnet [1]).

2) Sort the list of pairs.

3) Now scan the sorted list, starting at the second pair. For each pair, if you can combine it with the previous one, do so and continue to try until combining as long as possible. Two pairs [base1, bits1] and [base2, bits2] can be combined if bits1 == bits2 and base2 - base1 == 1 << (32 - bits1). In that case, the combination is [base1, bits1 - 1].

4) Finally, convert the pairs back into CIDR notation: the first integer is the base of the subnet (when converted back to dotted decimal) and the second integer is the bitwidth.

Both steps 2 and 3 are O(n log n)

Footnote 1: In your example, you don't include the addresses with last byte 0, which means my algorithm will fail in your test case. You'd have to add them to the list. This point reveals a subtle but important detail in the definition of what a CIDR subnet is: technically, the smallest possible subnet is /30, because both the first and last ip of the range are reserved. Consequently /31 would have no valid IP addresses. However, people often use the term CIDR subnet to mean "a bitmask which recognizes a set of IP addresses", as in their use as filter expressions.

share|improve this answer

Try as :

public class Test {
    public static void main(String[] args) {
        String[] ipArray1 = new String[]{"", "", "", ""};
        String[] ipArray2 = new String[ipArray1.length];
        for(int i=0; i < ipArray1.length; i++) {
            String temp = ipArray1[i];
            ipArray2[i] = temp.substring(0,6) + "0/24";
        for(String  ip : ipArray2) {

Output :
share|improve this answer
Are you kiddin'? What will happen if ip is like ip. substr will fail. I need an algorithmic solution or a library. Your solution is based on my input but with different input it will fail. –  denizeren Sep 21 '12 at 5:47
if so, why did not submit like that in your post completely? I just solve the problem as post. –  CycDemo Sep 21 '12 at 6:05
That's not even a real answer. Writing anything that just produces a given output is a waste of everyone's time. It clearly doesn't solve the very clearly posed question. –  sillyMunky Feb 5 '13 at 19:26

Your Answer


