Search code examples
javaip-address

Determine if net mask is valid in Java


What is the easiest way in Java 6 to determine whether a given address is a valid net mask? I have found one solution which basically creates an array of valid IPs to use in a comparison (i.e. "255.255.255.255", "255.255.255.254", "255.255.255.252", etc...). Is there an easier way or is this the best way?


Solution

  • If you're happy to include an external dependency, then Apache's commons.net may have what you're looking for.

    Have a look at SubnetUtils and its SubnetInfo nested class. You can construct a SubnetUtils with an IP address and a mask. The constructor throws an exception if your mask is invalid, and SubnetInfo.html#isInRange can tell you if an IP is in a mask's range.

    String subnetString = "20.38.1.5/24";
    String checkIP = "20.38.1.158";
    
    org.apache.commons.net.util.SubnetUtils subnet = new org.apache.commons.net.util.SubnetUtils(subnetString);
    org.apache.commons.net.util.SubnetUtils.SubnetInfo info = subnet.getInfo();
    System.out.println(checkIP + " is" + (info.isInRange(checkIP)?" ":" NOT " ) + "contained in " + subnetString);