java - 如何将 IPv6 地址转换为二进制字符串?

标签 java binary network-programming ipv6 data-conversion

如何将 IPv6 地址转换为二进制字符串?

示例:

IPv6:    2001:0db8:85a3:0000:0000:8a2e:0370:7334
Binary:  0010000000000001 0000110110111000 1000010110100011 0000000000000000 0000000000000000 1000101000101110 0000001101110000 0111001100110100 
<小时/>

我想用 Java 来做到这一点。这是我失败的尝试(我不要求与此尝试相关的解决方案):

用我更熟悉的C++实现:

#include <iostream>
#include <string>

#define _BSD_SOURCE
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

std::string toBinary(unsigned long int decimalIpV6)
{
    std::string r;
    while(decimalIpV6!=0) {r=(decimalIpV6%2==0 ?"0":"1")+r; decimalIpV6/=2;}
    return r;
}

unsigned long int ipV6toDecimal(std::string binaryString) {
    struct sockaddr_in antelope;    
    inet_aton(binaryString.c_str(), &antelope.sin_addr); // store IP in antelope
    // and this call is the same as the inet_aton() call, above:
    antelope.sin_addr.s_addr = inet_addr(binaryString.c_str());
    return antelope.sin_addr.s_addr;
}

int main() {
    std::string ipv6 = "192.168.0.0";
    unsigned long int ipv6decimal= ipV6toDecimal(ipv6);
    std::cout << toBinary(ipv6decimal) << std::endl;
    return 0;
}

这是有问题的,会产生错误的结果(“1010100011000000”)。

<小时/>

PS:有一个 IPv6 到二进制计算器 online ,这可能会对您测试时有所帮助。

最佳答案

尝试这个解决方案:

String ipv6 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334";
String[] spl = ipv6.split(":");
String result = "", del = "";
for (String s : spl) {
    result += del
            + String.format("%16s", new BigInteger(s, 16).toString(2)).replace(' ', '0');
    del = " ";
}
System.out.println(result);
<小时/>

如果您使用的是 Java 8,您可以使用:

String result = Stream.of(ipv6.split(":"))
      .map(s -> String.format("%16s", new BigInteger(s, 16).toString(2)).replace(' ', '0'))
      .collect(Collectors.joining(" "));

输出

0010000000000001 0000110110111000 1000010110100011 0000000000000000 0000000000000000 1000101000101110 0000001101110000 0111001100110100

关于java - 如何将 IPv6 地址转换为二进制字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47351267/

相关文章:

java - 静态 InetAddress.getLoopbackAddress() 返回什么?

java - 无法恢复值(value),为什么?

java - java中基数10到基数2,8,16的转换

java - 在 Java Card 中将整数的二进制表示形式转换为 ASCII

c - 补码截断?

c++ - select和UDP协议(protocol)结合时收不到数据

java - 尝试更改 RCP 中的配置文件位置,导致运行不同的程序

java - 使用 Spring-data 在 java.util.List 中插入 $currentDate

java - 为什么上传 servlet 返回访问被拒绝错误

C++ boost Asio : How do I have multiple clients?