Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect if an IP is in a network?

Tags:

java

ip

I found in python (lib ipaddress). It`s python example.

ip="1.232.12.3"
net="1.232.12.0/20"
ip in net

result true

Can I find this in Java?

like image 660
user2593968 Avatar asked Mar 23 '23 01:03

user2593968


1 Answers

What you're asking is if an IP is in a given cidr range. You could write your own code to figure out the start and end of the cidr and see if the IP falls in that range, or just use the Apache Commons Net library.

The SubnetUtils class does exactly what you want:

String cidrRange = "1.232.12.0/20";
String addr = "1.232.12.3";
SubnetUtils utils = new SubnetUtils(cidrRange);
boolean isInRange = utils.getInfo().isInRange(addr);
like image 154
Brian Roach Avatar answered Mar 31 '23 14:03

Brian Roach