IPv6 ip(fc00::) addr的长度非法 [英] IPv6 ip (fc00::) addr is of illegal length

查看:155
本文介绍了IPv6 ip(fc00::) addr的长度非法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将BigInteger转换为InetAddress时出现错误.仅当使用特定IP"fc00 ::"时才会发生这种情况.这是我的测试代码.如果我想念什么,请告诉我.

I am seeing the error while converting BigInteger to InetAddress. This happens only with a particular IP "fc00::". Here is my test code. Please let me know if I am missing something.

    public class IPv6Test {

          public static BigInteger ipv6ToNumber(InetAddress Inet6Address)
         {
         return new BigInteger(1,Inet6Address.getAddress());
         }

        public static void main(String[] args) throws UnknownHostException
        {

        InetAddress iaStart = InetAddress.getByName("fc00::");

                BigInteger biStart = ipv6ToNumber(iaStart);

        System.out.println(biStart.toString());


        System.out.println(InetAddress.getByAddress(biStart.toByteArray()).getHostAddress()) ;


 }

}

推荐答案

原因是BigInteger在biStart.toByteArray();中增加了一个额外的字节.

The reason is that BigInteger is tacking on an extra byte in biStart.toByteArray();

它给了您17个字节,这太长了,IPv6地址是16个字节.多余的字节位于高端,为0.

It is giving you 17 bytes, which is too long, an IPv6 address is 16 bytes. The extra byte is at the high end, and it is 0.

如果您在代码中执行此操作,那么它将起作用:

If you do this in your code, then it works:

 byte bytes[] = biStart.toByteArray();
 if(bytes.length > 16) {
        byte bytes2[] = new byte[16];
        System.arraycopy(bytes,  1,  bytes2,  0,  bytes2.length);
        bytes = bytes2; 
 }

如果您阅读BigInteger.bitLength()的javadoc,则表明大整数的二进制补码表示形式至少为 bitLength()+ 1位长. toByteArray()为您提供二进制补码表示法.由于您需要全部128位来表示该地址,并且您在谈论一个额外的位,因此最终只有17个字节.

If you read the javadoc for BigInteger.bitLength(), it indicates that the two's complement representation of the big integer will be at least bitLength() + 1 bits long. toByteArray() gives you the two's complement representation. Since you need all 128 bits to repesent this address, and you are talking on an extra bit, you end up with 17 bytes.

为什么要增加一个字节?那是因为您的地址是一个正数.但是最高字节是fc00,它的二进制补码变为负数.因此,高端必须有一个额外的0位,以使数字在2的补码中保持正数,因此2的补码表示需要129位或17个字节,而不是128位和16个字节.对于最高位为1的任何地址,或以8xxx到fxxx开头的任何地址(例如fc00),都会发生这种情况.

Why is there an extra byte? That is because your address is a positive number. But the highest byte is fc00, which in two's complement becomes a negative number. So there must be an extra 0 bit at the high end to keep the number positive in two's complement, and thus the two's complement representation takes 129 bits or 17 bytes, not 128 bits and 16 bytes. This will occur for any address with 1 in the very highest bit, or any address which starts with 8xxx to fxxx, such as fc00.

这篇关于IPv6 ip(fc00::) addr的长度非法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆