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

2019-05-07 21:05发布

问题:

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?

回答1:

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


标签: java ip