Example:
        255.0.0.0 to 8
        255.255.0.0 to  16
        255.255.255.0 to 24

 

public class convertIpFormatToNetmaskCIDR {
    public static void main(String[] args) {
        int netmaskCIDR = 0;
        String netmask = "255.255.0.0";
        String[] st = netmask.split("\\.");
        if (st.length != 4)
            throw new NumberFormatException("Invalid netmask address: " + netmask);

        if (Integer.parseInt(st[0]) < 255) {
            throw new NumberFormatException("The first byte of netmask can not be less than 255");
        }
        
        for (int i = 0; n < st.length; i++) {
            int v = Integer.parseInt(st[i]);
            if (v != 0) {
                netmaskCIDR += Integer.toBinaryString(v).length();
            }
        }
        // Output: 16
        System.out.println(netmaskCIDR);
    }
}

arrow
arrow
    全站熱搜

    dreamtails 發表在 痞客邦 留言(0) 人氣()