Converting CIDR address to subnet mask and network address

73,749

Solution 1

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

Solution 2

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

Solution 3

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
    }

Solution 4

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>

Solution 5

Linux command line ipcalc. You can quickly use :

$ipcalc 192.168.10.0/24
Address:   192.168.10.0         11000000.10101000.00001010. 00000000
Netmask:   255.255.255.0 = 24   11111111.11111111.11111111. 00000000
Wildcard:  0.0.0.255            00000000.00000000.00000000. 11111111
=>
Network:   192.168.10.0/24      11000000.10101000.00001010. 00000000
HostMin:   192.168.10.1         11000000.10101000.00001010. 00000001
HostMax:   192.168.10.254       11000000.10101000.00001010. 11111110
Broadcast: 192.168.10.255       11000000.10101000.00001010. 11111111
Hosts/Net: 254                   Class C, Private Internet
Share:
73,749
Dmitry
Author by

Dmitry

Updated on February 07, 2020

Comments

  • Dmitry
    Dmitry about 4 years

    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)
  • username
    username over 12 years
    /*** approximation in javascript. since i needed this for myself, i may as well share ***/ function cidrToMask ( cidrStr ) { var parts = cidrStr.split('/'); var ipStr = parts[0]; var prefix = (parts.length < 1) ? 0 : Number( parts[1] ); var mask = 0xffffffff << (32 - prefix); var maskStr = [ (mask >>> 24) , (mask >> 16 & 0xff) , (mask >> 8 & 0xff) , (mask & 0xff) ].join('.'); alert( "Prefix=" + prefix + "\n" + "Address=" + ipStr + "\n" + "Mask=" + maskStr ); }; cidrToMask ( '192.168.10.0/24' );
  • Olgun Kaya
    Olgun Kaya over 12 years
    it seems the utility have a problem with just one address notification. I mean; let's say the ip is just one ip. so if I want to use it like ip/32 than it fails. or I am using it in the wrong way.
  • Jan H
    Jan H almost 11 years
    github.com/edazdarevic/CIDRUtils gives you IPv6 support and a test to see if an IP address is in the range or not. Mask length is missing though. See this answer stackoverflow.com/questions/558038/…
  • logoff
    logoff about 10 years
    @OlgunKaya you are using it in the wrong way, the constructor showed in the answer expects CIDR notation, it is IP_address/MASK not only IP_address.
  • Mark Chorley
    Mark Chorley about 8 years
    Welcome. You could improve this answer by explaining how it solves the problem posed in the question.
  • Renato
    Renato almost 8 years
    this is mostly ugly Java code with just a couple of "def"s. In proper Groovy this would be half the size.
  • Jeff Vincent
    Jeff Vincent over 7 years
    Is this available as a Maven dependency?
  • Sean F
    Sean F over 7 years
    it will be shortly, I will update the project page when it is
  • Sean F
    Sean F about 7 years
    now it is, it is now in maven central repo: repo1.maven.org/maven2/com/github/seancfoley/ipaddress/2.0.0
  • Nagabhushan S N
    Nagabhushan S N almost 6 years
    getNetmask() returns the SubnetMask (255.255.255.0). If I want to get prefix length (24), is there any method? I couldn't find
  • Michael Sims
    Michael Sims almost 6 years
    Ive read the docs, Ive experimented ... is there an easy way to get - for example - an array of all pingable IP addresses from say ... your subnet class? Or do I have to re-construct the addresses from the lower and upper address?
  • Sean F
    Sean F almost 6 years
    Well, you can only tell if an address is pingable by getting that address and pinging it. So you'd have to try pinging each one. To get each address you could just iterate through the subnet: for(IPAddress addr : new IPAddressString("192.168.10.0/24").getAddress()) { ... }
  • Sayantan Ghosh
    Sayantan Ghosh about 5 years
    SubnetUtils does not support IPv6, how to achieve the same for ipv6?
  • Ahmed Rezk
    Ahmed Rezk about 4 years
    macos: brew install ipcalc
  • Michael Sims
    Michael Sims about 4 years
    @SeanF I was hoping there was some fancy-dancy class out there that did the work for me ... ;-)
  • Sean F
    Sean F almost 4 years
    @MichaelSims and your hopes were answered :-)
  • Michael Sims
    Michael Sims almost 4 years
    @SeanF Actually, I had to do it like this: for(IPAddress addr: new IPAddressString("10.10.10.0/24").toSequentialRange().getIter‌​able()){ ... } - But it worked, except for I had to figure out how to isolate the .0 address from my .isReachable because Java says I don't have permission to ping the network address ... go figure :-)