Getting error when checking if IP is in subnet range in Java

I am using the below code to check if the IP address is within a given subnet range. It works fine for the network prefix from 0 to 31. But when I give the network prefix as 32 it gives a lower range and a 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 with the above approach or is there another possible way to effectively control the Ip range.

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

bottom address: 0.0.0.0

higher address: 0.0.0.0

falsely

+3


source to share


1 answer


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 inclusive is false.



I assume you set this flag to true

before checking addresses:

SubnetUtils utils = new SubnetUtils(ipRange);
utils.setInclusiveHostCount(true);

      

+8


source







All Articles