问题
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