Search code examples
javanetwork-programmingapache-commons-netcidr

Apache-commons-net Illegal (yet legal) CIDR notation


I need the ability to work with CIDR notation in Java.

I found the commons library SubnetUtils.

When I try to use a CIDR of 10.10.0.0/22, as an example I get the following

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: Could not parse [10.10.0.0] at org.apache.commons.net.util.SubnetUtils.calculate(SubnetUtils.java:240) at org.apache.commons.net.util.SubnetUtils.<init>(SubnetUtils.java:52)

The code that is calling is:

SubnetUtils subnetUtils = new SubnetUtils(cidrNotation); SubnetInfo info = subnetUtils.getInfo();

I see that SubnetUtils is checking the bits to see if the mask is valid.

` From SubnetUtils.java

 private void calculate(String mask) {
    Matcher matcher = cidrPattern.matcher(mask);

    if (matcher.matches()) {
        address = matchAddress(matcher);

        /* Create a binary netmask from the number of bits specification /x */
        int cidrPart = rangeCheck(Integer.parseInt(matcher.group(5)), 0, NBITS);
        for (int j = 0; j < cidrPart; ++j) {
            netmask |= (1 << 31-j);
        }

        /* Calculate base network address */
        network = (address & netmask);

        /* Calculate broadcast address */
        broadcast = network | ~(netmask);
    } else {
        throw new IllegalArgumentException("Could not parse [" + mask + "]");
    }

`

I realize 10.0.0.0/8 is a class A, but I should legally be able to chop it into smaller pieces.

Is there a way around this? A better Utility? Or am I stuck rewriting SubnetUtils?


Solution

  • I continued to investigate and it turns out that deep in the recursion I lost the mask on my CIDR. the first number of passes was ok then in an exception path it was lost. The utility works as expected.