Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting error while Checking if an IP is in a subnet range in Java

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

like image 441
user3244519 Avatar asked Dec 14 '22 19:12

user3244519


1 Answers

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);
like image 77
Cristian Greco Avatar answered Jan 12 '23 00:01

Cristian Greco