Converting CIDR notation into IP range without other library


I want to find the IP range from CIDR. For example, I input "". How do I calculate the IP range in Java?

I only can change the IP address and subnet mask to byte[]. But I don't know how to merge them. This is my code.

String str = "";
String[] cidr = str.split("/");
String[] buf = cidr[0].split(".");
byte[] ip = new byte[] { 
                (byte)Integer.parseInt(buf[0]), (byte)Integer.parseInt(buf[1]),(byte)Integer.parseInt(buf[2]), (byte)Integer.parseInt(buf[3])

int mask = 0xffffffff << (32 - Integer.parseInt(cidr[1]));
        int value = mask;
        byte[] subnet = new byte[] {
                (byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff)

asked on Stack Overflow Jun 1, 2020 by samsam_rabbit

1 Answer


First thing you need to do is fix the regex, because . has special meaning: cidr[0].split("\\.");

Then, to build the from and to addresses of the IP range, using bitwise AND, OR, and NOT:

byte[] from = new byte[4];
byte[] to = new byte[4];
for (int i = 0; i < to.length; i++) {
    from[i] = (byte) (ip[i] & subnet[i]);
    to[i] = (byte) (ip[i] | ~subnet[i]);

Finally, print the result:

System.out.printf("%d.%d.%d.%d - %d.%d.%d.%d%n",
        Byte.toUnsignedInt(from[0]), Byte.toUnsignedInt(from[1]),
        Byte.toUnsignedInt(from[2]), Byte.toUnsignedInt(from[3]),
        Byte.toUnsignedInt(to[0]), Byte.toUnsignedInt(to[1]),
        Byte.toUnsignedInt(to[2]), Byte.toUnsignedInt(to[3]));

Output -

FYI: The code fails for /0 because to mask value ends up wrong. I'll leave that as an exercise for you to fix that.

answered on Stack Overflow Jun 1, 2020 by Andreas • edited Jun 1, 2020 by Andreas

User contributions licensed under CC BY-SA 3.0