Search code examples
javaapache-commons-netnetmask

Inverting netmask using commons SubnetUtils.SubnetInfo.getNetmask() in Java


Lets say I have this:

SubnetUtils utils = new SubnetUtils("192.168.1.0/24");
utils.getInfo().getNetmask() // = 255.255.255.0

Is there a easy way of getting the mask inverted (Cisco ACL style)?

eg.: 0.0.0.255

Solution

  • I put up a code that might work for your case. However, maybe there is a library that does it in a more optimized way?

        public String reverseMask(String mask) {
           String[] octets = mask.split("\\.");
           StringBuilder sb = new StringBuilder();
           for (int i=0;i<4;i++) {
             sb.append(String.valueOf(0xFF ^ Integer.valueOf(octets[i])))
               .append(i==3 ? "" : ".");
           }
           return sb;
        }