IP地址的CIDR

时间:2016-08-08 23:33:13

标签: java ip-address ipv4 subnet cidr

我正在尝试找到IP地址的子网掩码,到目前为止我能够做得很好。但唯一的问题是CIDR药水。我从这里和那里得到了一些例子并组装了代码。

到目前为止,这就是我所拥有的:

public class Test {

int baseIPnumeric;
int netmaskNumeric;

/**
 * Specify IP in CIDR format like: new IPv4("10.1.0.25/16");
 *
 *@param IPinCIDRFormat
 */
public void doInitialize(String IPinCIDRFormat) throws NumberFormatException {

    String[] st = IPinCIDRFormat.split("\\/");
    if (st.length != 2)

        throw new NumberFormatException("Invalid CIDR format '"
                + IPinCIDRFormat + "', should be: xx.xx.xx.xx/xx");

    String symbolicIP = st[0];
    String symbolicCIDR = st[1];

    Integer numericCIDR = new Integer(symbolicCIDR);
    if (numericCIDR > 32)

        throw new NumberFormatException("CIDR can not be greater than 32");

    /* IP */
    st = symbolicIP.split("\\.");

    if (st.length != 4)
        throw new NumberFormatException("Invalid IP address: " + symbolicIP);

    int i = 24;
    baseIPnumeric = 0;

    for (int n = 0; n < st.length; n++) {

        int value = Integer.parseInt(st[n]);

        if (value != (value & 0xff)) {

            throw new NumberFormatException("Invalid IP address: " + symbolicIP);
        }

        baseIPnumeric += value << i;
        i -= 8;

    }

    /* netmask from CIDR */
    if (numericCIDR < 8)
        throw new NumberFormatException("Netmask CIDR can not be less than 8");
    netmaskNumeric = 0xffffffff;
    netmaskNumeric = netmaskNumeric << (32 - numericCIDR);

}



/**
 * Get the net mask in symbolic form, i.e. xxx.xxx.xxx.xxx
 *
 *@return
 */

public String getNetmask() {
    StringBuffer sb = new StringBuffer(15);

    for (int shift = 24; shift > 0; shift -= 8) {

        // process 3 bytes, from high order byte down.
        sb.append(Integer.toString((netmaskNumeric >>> shift) & 0xff));

        sb.append('.');
    }
    sb.append(Integer.toString(netmaskNumeric & 0xff));

    return sb.toString();
}

/**
 *@param args
 */
public static void main(String[] args) { 

    Test ipv4 = new Test(); 
    String IP = "192.168.161.111";
    ipv4.doInitialize(IP+"/32");
    System.out.println(ipv4.getNetmask());

}

}

我只需要知道我传递/ 32作为CIDR附加到IP,它是否总是32,如果不是,我怎么知道哪一个放在那里?

0 个答案:

没有答案
相关问题