Converting CIDR address to subnet mask and network address
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());
The IPAddress Java library supports both IPv4 and IPv6 in a polymorphic manner including subnets. The javadoc is available at the link. Disclaimer: I am the project manager.
All the use cases you listed are supported for both IPv4 and Ipv6 transparently.
String str = "192.168.10.0/24";
IPAddressString addrString = new IPAddressString(str);
try {
IPAddress addr = addrString.toAddress();
Integer prefix = addr.getNetworkPrefixLength(); //24
IPAddress mask = addr.getNetwork().getNetworkMask(prefix, false);//255.255.255.0
IPAddress networkAddr = addr.mask(mask); //192.168.10.0
IPAddress networkAddrOtherWay = addr.getLower().removePrefixLength(); //192.168.10.0
...
} catch(AddressStringException e) {
//e.getMessage provides validation issue
}
Following Yuriy's answer: To get the whole range of ip addresses, the Apache Java class SubnetUtils offers the following methods:
String[] addresses = utils.getInfo().getAllAddresses();
To download the jar containing the class go to: http://repo1.maven.org/maven2/commons-net/commons-net/3.0.1/commons-net-3.0.1.jar
The source code: http://svn.apache.org/viewvc/commons/proper/net/trunk/src/main/java/org/apache/commons/net/util/SubnetUtils.java?view=markup
Maven id:
<groupId>commons-net<groupId> <artifactId>
commons-net<artifactId> <version>
3.0.1<version>