10

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

2 Answers 2

22

try this

    InetAddress a = InetAddress.getByName("2001:0DB8:AC10:FE01:0000:0000:0000:0000");
    byte[] bytes = a.getAddress();
Sign up to request clarification or add additional context in comments.

Comments

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.