Ad

How Do I Convert Hex (buffer) To IPv6 In Javascript

- 1 answer

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.

Ad

Answer

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"
Ad
source: stackoverflow.com
Ad