Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting CIDR address to subnet mask and network address

Given a CIDR address, e.g. 192.168.10.0/24

  • How to determine mask length? (24)
  • How to determine mask address? (255.255.255.0)
  • How to determine network address? (192.168.10.0)
like image 258
Dmitry Avatar asked May 31 '10 08:05

Dmitry


People also ask

How do you find the CIDR from an IP address and a subnet mask?

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.

Is CIDR and subnet mask the same?

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.

What is the mask 255.255 255.0 in CIDR notation?

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.


2 Answers

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); 
like image 83
Yuriy Avatar answered Sep 16 '22 17:09

Yuriy


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()); 
like image 42
ZZ Coder Avatar answered Sep 20 '22 17:09

ZZ Coder