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.
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
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.