I am using the below code to check if an IP address is within the given subnet range. It is working fine for network prefix from 0 to 31. But when i give network prefix value as 32, it is giving lower range and higher range as 0.0.0.0 instead of 10.198.23.4. I am using commons-net-3.3 jar. Is there anything wrong in the above approach or is other posiible way to check Ip range efficiently.
public class TestIPRange {
public static void main(String[] args) {
String ipRange = "10.198.23.4/32";
String clientIp = "10.198.23.4";
SubnetUtils utils = new SubnetUtils(ipRange);
System.out.println("lower address: " + utils.getInfo().getLowAddress());
System.out.println("higher address: " + utils.getInfo().getHighAddress());
System.out.println(utils.getInfo().isInRange(clientIp));
}
}
Outputs
lower address: 0.0.0.0
higher address: 0.0.0.0
false
Check the javadoc for SubnetInfo#getLowAddress()
:
Return the low address as a dotted IP address. Will be zero for CIDR/31 and CIDR/32 if the inclusive flag is false.
I guess you shoud set this flag to true
before checking addresses:
SubnetUtils utils = new SubnetUtils(ipRange);
utils.setInclusiveHostCount(true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With