3

I need to convert the IP Subnet Mask like say 24 to 255.255.255.0 or say 23 to 255.255.254.0 in Java. Is there any API that I can use ?

thanks.

j10
  • 2,009
  • 3
  • 27
  • 44

2 Answers2

7

Without any libraries :

int cidrMask = 23;
long bits = 0;
bits = 0xffffffff ^ (1 << 32 - cidrMask) - 1;
String mask = String.format("%d.%d.%d.%d", (bits & 0x0000000000ff000000L) >> 24, (bits & 0x0000000000ff0000) >> 16, (bits & 0x0000000000ff00) >> 8, bits & 0xff);

>>255.255.254.0

Have to use a long because of missing unsigned types in Java

gma
  • 2,563
  • 15
  • 14
  • I love how compact this is. Stick all that code in a method `public String cidrToMask(int cidr) {...}` add a potato, some carrots, and baby, you've got a stew! – JohnFilleau Jun 12 '13 at 15:42
  • gma thanks for the compact code. But i have a question when the cidrMask is 0 what will be the subnet mask in dotted decimal form. will it be 0.0.0.0 or 255.255.255.255 ? – j10 Jun 18 '13 at 17:15
  • you can try :) : `255.255.255.255` – gma Jun 19 '13 at 06:59
  • gma : On searching online I found that cidrMask 0 corresponds to 0.0.0.0 and not 255.255.255.255. I just checked on Wikipedia as well http://en.wikipedia.org/wiki/Default_route (checkout the References) – j10 Jul 01 '13 at 16:22
0

http://commons.apache.org/proper/commons-net/apidocs/index.html?org/apache/commons/net/util/SubnetUtils.html

I followed NeplatnyUdaj's comment, and it looks like you can construct a SubnetUtils object to get the mask:

    int mask = 3;
    String cidr = "255.255.255.255/" + mask;
    SubnetUtils subnet = new SubnetUtils(cidr);

    String stringMask = subnet.getInfo().getNetmask();

    System.out.println("The subnet mask is: " + stringMask);

That's what I used, and it worked for me. Infact, using the getNetmask() method makes the IP string you use to construct the cidr String arbitrary.

JohnFilleau
  • 4,045
  • 1
  • 15
  • 22