iginpq
Last Updated: February 25, 2016
·
4.07K
· saeidzebardast

Validating Subnet and CIDR format in Java

Apache Commons Net is a great library which implements the client side of many basic Internet protocols. I use SubnetUtils class for validating CIDR format and Subnet value.
The following methods are for checking CIDR format and Subnet value in Java:

public static boolean isValidSubnetFormat(String subnet) {
    try {
        SubnetUtils subnetUtils = new SubnetUtils(subnet);
        return true;
    } catch (IllegalArgumentException e) {
        return false;
    }
}

public static boolean isValidSubnet(String subnet) {
    try {
        SubnetUtils subnetUtils = new SubnetUtils(subnet);
        return subnetUtils.getInfo().getAddress().equals(subnetUtils.getInfo().getNetworkAddress());
    } catch (IllegalArgumentException e) {
        return false;
    }
}

1 Response
Add your response

16716

In isValidSubnetFormat(), you don't need the local variable.
In isValidSubnet(), you should save subnetUtils.getInfo() in a local variable.

over 1 year ago ·