Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java IPv6 Address String to Bytes

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

like image 506
user2514661 Avatar asked Jun 24 '13 03:06

user2514661


2 Answers

try this

    InetAddress a = InetAddress.getByName("2001:0DB8:AC10:FE01:0000:0000:0000:0000");
    byte[] bytes = a.getAddress();
like image 104
Evgeniy Dorofeev Avatar answered Nov 12 '22 06:11

Evgeniy Dorofeev


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
}
like image 1
Sean F Avatar answered Nov 12 '22 06:11

Sean F