0

我正在尝试根据掩码增加 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

你能找到我做错的地方吗?

4

1 回答 1

0

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

于 2012-09-06T09:29:31.187 回答