Java IPv6 ip(fc00::)地址的长度非法
我在将BigInteger转换为InetAddress时看到错误。这仅在特定IP“fc00::”时发生。这是我的测试代码。如果我遗漏了什么,请告诉我Java IPv6 ip(fc00::)地址的长度非法,java,ipv6,Java,Ipv6,我在将BigInteger转换为InetAddress时看到错误。这仅在特定IP“fc00::”时发生。这是我的测试代码。如果我遗漏了什么,请告诉我 public class IPv6Test { public static BigInteger ipv6ToNumber(InetAddress Inet6Address) { return new BigInteger(1,Inet6Address.getAddress());
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()中附加了一个额外的字节 它给你17个字节,太长了,IPv6地址是16个字节。额外的字节在高端,它是0 如果在代码中执行此操作,则它将起作用:
byte bytes[] = biStart.toByteArray();
if(bytes.length > 16) {
byte bytes2[] = new byte[16];
System.arraycopy(bytes, 1, bytes2, 0, bytes2.length);
bytes = bytes2;
}
如果读取biginger.bitLength()的javadoc,则表明这两个大整数的补码表示形式至少为
bitLength()+1位长。toByteArray()为您提供了这两者的补码表示。由于您需要所有128位来重新发送此地址,并且您正在使用额外的位进行交谈,因此最终得到17个字节
为什么会有一个额外的字节?那是因为你的地址是正数。但是最高的字节是fc00,它在两个补码中变成负数。因此,高端必须有一个额外的0位来保持2的补码中的数字为正,因此2的补码表示需要129位或17字节,而不是128位和16字节。对于最高位为1的任何地址,或以8xxx到fxxx开头的任何地址,如fc00,都会发生这种情况。这不是有效的IP v6。就这么简单,@LorenzMeyer说什么;然而,这是一个给定的错误消息,你得到的是相当混乱。。。