blueren
blueren

Reputation: 2860

How do I convert hex (buffer) to IPv6 in javascript

I have a buffer that contains a hex representation of an IPv6 address. How exactly do I convert it to an actual IPv6 representation?

// IP_ADDRESS is a buffer that holds the hex value of the IPv6 addr.

let IP_ADDRESS_HEX = IP_ADDRESS.toString('hex'); 
// 01000000000000000000000000000600

I don't actually mind using a simple lib if it offers a conversion function.

Upvotes: 1

Views: 1015

Answers (2)

Hans Koch
Hans Koch

Reputation: 4481

If your IP_ADDRESS_HEX always has the same size, you can do the following. If not you need to pad the string as well.

'01000000000000000000000000000600'
    .match(/.{1,4}/g)
    .join(':')

// "0100:0000:0000:0000:0000:0000:0000:0600"

You can also shorten certain blocks, but this is not a necessity eg ffff:0000:0000:0000:0000:0000 would become ffff:: but both are valid.

If you still want it full spec you can do it like this

'01000000000000000000000000000600'
  .match(/.{1,4}/g)
  .map((val) => val.replace(/^0+/, ''))
  .join(':')
  .replace(/0000\:/g, ':')
  .replace(/:{2,}/g, '::')

// "100::600"

Upvotes: 3

banban
banban

Reputation: 36

I do not know if I really answer to your question, but to convert the string IP_ADDRESS_HEX to an IPv6 address representation, I would use String.slice() to split IP_ADDRESS_HEX in 8 groups and use String.join() to add the ":" between these groups.

var IP_ADDRESS_HEX = "01000000000000000000000000000600";
var i = 0;
var a = [];
while (i != 8) {
    a[i] = IP_ADDRESS_HEX.slice(i * 4, (i * 4) + 4);
    i++;
}
result = a.join(":");

Of course, it only works when IP_ADDRESS_HEX has exactly 32 characters.

Upvotes: 1

Related Questions