I have ip addresses and a mask such as 10.1.1.1/32
. I would like to check if 10.1.1.1
is inside that range. Is there a library or utility that would do
This is just a few lines of code with the open-source IPAddress Java library. Disclaimer: I am the project manager of the IPAddress library.
String subnetStr = "10.1.1.1/24";
String addrStr = "10.1.1.1";
IPAddress subnetAddress = new IPAddressString(subnetStr).getAddress();
IPAddress subnet = subnetAddress.toPrefixBlock();
IPAddress testAddress = new IPAddressString(addrStr).getAddress();
boolean result = subnet.contains(testAddress);
System.out.println(subnetAddress + " is in subnet " + subnet + " and " +
(result ? "contains" : "does not contain") + " address " + testAddress);
Output:
10.1.1.1/24 is in subnet 10.1.1.0/24 and contains address 10.1.1.1