user2593968
user2593968

Reputation: 59

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

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?

Upvotes: 4

Views: 4286

Answers (1)

Brian Roach
Brian Roach

Reputation: 76898

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);

Upvotes: 7

Related Questions