get IP Subnet Mask - Java Network

Java examples for Network:IP Address

Description

get IP Subnet Mask

Demo Code


import java.util.ArrayList;
import java.util.regex.Pattern;

public class Main{
    public static void main(String[] argv) throws Exception{
        int cidr = 2;
        System.out.println(getSubnetMask(cidr));
    }/*  w w w  .  j  a  v a  2  s.c om*/
    public static String getSubnetMask(final int cidr)
            throws InvalidIPAddressException {
        return numberToIP(getSubnetMaskNumeric(cidr));
    }
    public static String numberToIP(long addr)
            throws InvalidIPAddressException {

        if (addr < 0L || addr > 4294967295L) {
            throw new InvalidIPAddressException("Invalid IP");
        }

        StringBuilder ip = new StringBuilder();

        ip.append((addr >> 24) & 0xFF).append(".");
        ip.append((addr >> 16) & 0xFF).append(".");
        ip.append((addr >> 8) & 0xFF).append(".");
        ip.append((addr) & 0xFF);

        return ip.toString();
    }
    public static long getSubnetMaskNumeric(final int cidr)
            throws InvalidIPAddressException {

        if (cidr > 32 || cidr < 0)
            throw new InvalidIPAddressException(
                    "CIDR can not be greater than 32");

        // starting /24 netmask, in decimal (255.255.255.0)
        long netmask = 4294967040L;

        // calculating and correcting netmask
        if (cidr > 24) {
            for (long i = cidr; i > 24; i--) {
                netmask += (long) (java.lang.Math.pow(2, (32 - i)));
            }
        } else if (cidr < 24) {
            for (long i = cidr; i < 24; i++) {
                netmask -= (long) (java.lang.Math.pow(2, (32 - (i + 1))));
            }
        }

        return netmask;
    }
}

Related Tutorials