4

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?

Maroun
  • 94,125
  • 30
  • 188
  • 241
user2593968
  • 59
  • 1
  • 2
  • Try taking a look at [InetAddress#isReachable](http://docs.oracle.com/javase/7/docs/api/java/net/InetAddress.html#isReachable%28int%29) – MadProgrammer Jul 25 '13 at 08:46
  • you should write this as an answer, so question this is marked as answered from the outside :) – Arno Saxena Jul 25 '13 at 09:03
  • `isReachable()` does not tell if an IP address is in the same network, it does just some kind of ping to a possibly remote node. – Gyro Gearless Jul 25 '13 at 09:06
  • Maybe this one helps: http://stackoverflow.com/questions/2942299/converting-cidr-address-to-subnet-mask-and-network-address – Gyro Gearless Jul 25 '13 at 09:09

1 Answers1

7

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);
Brian Roach
  • 76,169
  • 12
  • 136
  • 161