如何在java中增加基于掩码的ipv6地址?

时间:2012-09-06 08:50:02

标签: operators inetaddress

我正在尝试根据掩码增加ipv6地址。 当有F代替增量时,我遇到了问题。 任何人都可以检查这个

public String IncrementIPV6ForPrefixLength (String IPv6String, int times) throws UnknownHostException
{

    int result , carry = 0, i;
    int bits;

    int mask=0;
    int index=IPv6String.indexOf("/");
    mask=Integer.parseInt(IPv6String.substring(index+1, IPv6String.length()));
    IPv6String=IPv6String.substring(0, index);

    InetAddress iaddr=InetAddress.getByName(IPv6String);
    byte[] IPv6Arr=iaddr.getAddress();
    if(mask > 128 || mask < 0)
        return null;

    i = mask/8;
    bits = mask%8;

    if(bits>0)
    {
        result = ((int)(IPv6Arr[i]>>(8-bits))) + times;
        IPv6Arr[i] =(byte) ((result << (8-bits)) | (IPv6Arr[i] & (0xff >> (bits))));
        carry = (result << (8-bits))/256;
        times /= 256;
    }
    i--;

    for(;i>=0;i--)
    {
        result = ((int)IPv6Arr[i]) + ((times + carry)& 0xFF);
        IPv6Arr[i] = (byte)(result % 256);
        carry = result / 256;
        if(carry == 0)
        {
            iaddr=InetAddress.getByAddress(IPv6Arr);
            String s=iaddr.toString();
            if(s.indexOf('/') != -1){
                s = s.substring(1, s.length()).toUpperCase();
            }
            StringBuffer buff =new StringBuffer("");
            String[] ss = s.split(":");
            for(int k=0;k<ss.length;k++){
                int Differ = 4 - ss[k].length();
                for(int j = 0; j<Differ;j++){
                    buff.append("0");
                }
                buff.append(ss[k]);
                if(k!=7)buff=buff.append(":");
            }
            return buff.toString()+"/"+mask;
        }
        times /= 256;
    }
    return null;
}
像这样输入:

FD34:4FB7:FFFF:A13F:1325:2252:1525:325F/48
FD34:41B7:FFFF::/48
FD34:4FBF:F400:A13E:1325:2252:1525:3256/35
像这样的输出 如果增加1

FD34:4FB8:0000:A13F:1325:2252:1525:325F/48
FD34:41B8:0000::/48
FD34:4FC0:0400:A13E:1325:2252:1525:3256/35

如果增加2

FD34:4FB8:0001:A13F:1325:2252:1525:325F/48
FD34:41B8:0001::/48
FD34:4FC0:1400:A13E:1325:2252:1525:3256/35
你可以找到我做错的地方。

1 个答案:

答案 0 :(得分:0)

忽略发布的代码,尝试将操作建模为对IPv6地址实际为128位数的直接数字运算。转换为BigInteger并使用BigInteger.add