Java IPv6 Address String to Bytes

左心房为你撑大大i 提交于 2019-12-23 08:06:16

问题


How can I convert a String containing the ipv6's machine packet destination to a 16 byte array? I know about getBytes and encodings, but I can't seem to understand which encoding I should use or if I have to convert that String to Hexadecimal or not.

String ipv6 = "2001:0DB8:AC10:FE01:0000:0000:0000:0000";
byte[] bytes = ipv6.getBytes(); //must be a 16 byte array

An example of what I wanna do, just to exemplify. Obs.: I have to convert the String to a 16 byte array Thanks


回答1:


try this

    InetAddress a = InetAddress.getByName("2001:0DB8:AC10:FE01:0000:0000:0000:0000");
    byte[] bytes = a.getAddress();



回答2:


The open-source IPAddress Java library will handle a wide range of IPv6addresses, so it can be used if your string need validation or has a wide variety of formats. Disclaimer: I am the project manager of that library.

Example code:

String ipv6 = "::1";
try {
    IPAddressString str = new IPAddressString("::1");
    IPAddress addr = str.toAddress();
    byte[] bytes = addr.getBytes();`
} catch(IPAddressStringException e) {
    //e.getMessage has validation error
}


来源:https://stackoverflow.com/questions/17267670/java-ipv6-address-string-to-bytes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!