Determine if net mask is valid in Java

ip-address, java

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.

Problem

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?

Original source