Given a CIDR address, e.g. 192.168.10.0/24
24
)255.255.255.0
)192.168.10.0
)The CIDR number is typically preceded by a slash “/” and follows the IP address. For example, an IP address of 131.10. 55.70 with a subnet mask of 255.0. 0.0 (which has 8 network bits) would be represented as 131.10.
CIDR notation is really just shorthand for the subnet mask, and represents the number of bits available to the IP address. For instance, the /24 in 192.168. 0.101/24 is equivalent to the IP address 192.168. 0.101 and the subnet mask 255.255.
The CIDR number comes from the number of ones in the subnet mask when converted to binary. The subnet mask 255.255. 255.0 is 11111111.11111111.
It is covered by apache utils.
See this URL: http://commons.apache.org/proper/commons-net/apidocs/org/apache/commons/net/util/SubnetUtils.html
String subnet = "192.168.0.3/31"; SubnetUtils utils = new SubnetUtils(subnet); utils.getInfo().isInRange(address)
Note: For use w/ /32 CIDR subnets, for exemple, one needs to add the following declaration :
utils.setInclusiveHostCount(true);
This is how you would do it in Java,
String[] parts = addr.split("/"); String ip = parts[0]; int prefix; if (parts.length < 2) { prefix = 0; } else { prefix = Integer.parseInt(parts[1]); } int mask = 0xffffffff << (32 - prefix); System.out.println("Prefix=" + prefix); System.out.println("Address=" + ip); int value = mask; byte[] bytes = new byte[]{ (byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff) }; InetAddress netAddr = InetAddress.getByAddress(bytes); System.out.println("Mask=" + netAddr.getHostAddress());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With