Matching an ip address to a table of subnet masks... What is the best approach in Java?

Remember, that IP address is just an int value for historic reasons represented as 4 octets in decimal form.

For the same token, the subnet is really a range of consecutive ints from network address to a broadcast address.

Therefore if your IP address object has an int converter, you can simply check if that integer is in range of the subnet by doing simple int comparisons.


Apache Commons Net has a SubnetUtils for this sort of thing, including determining if a given IP address is within a given subnet.

Trivial example:

    String[] subnetsMasks = { ... };
    Collection<SubnetInfo> subnets = new ArrayList<SubnetInfo>();
    for (String subnetMask : subnetsMasks) {
        subnets.add(new SubnetUtils(subnetMask).getInfo());
    }

    String ipAddress = ...;
    for (SubnetInfo subnet : subnets) {
        if (subnet.isInRange(ipAddress)) {
            System.out.println("IP Address " + ipAddress + " is in range " + subnet.getCidrSignature());
        }
    }