Home > Java Core > Convert CIDR notation to IP Range in Java

Convert CIDR notation to IP Range in Java

What is CIDR?

CIDR stands for – Classless Inter-Domain Routing (CIDR), also called supernetting.

It is a way to allocate Internet Protocol (IP) addresses by creating unique and more granular identifiers for networks and devices.

The objective of CIDR was to address scalability issues with classful IP addresses based on three classes –
– Class A – capacity is 16,581,375 IP addresses
– Class B – capacity is 65,536 IP addresses
– Class C – capacity is 256 IP addresses

CIDR allows IP addresses to be variable and not bound by the size limitations of Classes A, B, and C. CIDR can organize IP addresses into subnetworks independent of the value of the addresses themselves.

Below is the java code which list downs all the IP addresses, belongs to the give CIDR notation.


import org.apache.commons.net.util.SubnetUtils;

import java.util.Arrays;

public class CommonUtils {
    public static void main(String[] args) {
        SubnetUtils utils = new SubnetUtils("168.25.0.0/22");
        String[] allIps = utils.getInfo().getAllAddresses();
        Arrays.stream(allIps).forEach(s -> {
            System.out.println(s);
        });
    }
}

And the output of the above code is

168.25.0.1
168.25.0.2
.
.
.
168.25.0.254
168.25.0.255
168.25.1.0
168.25.1.1
.
.
.
168.25.1.254
168.25.1.255
168.25.2.0
168.25.2.1
.
.
.
168.25.2.254
168.25.2.255
168.25.3.0
168.25.3.1
.
.
.
168.25.3.253
168.25.3.254