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 va
Solution 1:
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"
Solution 2:
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.
Post a Comment for "How Do I Convert Hex (buffer) To Ipv6 In Javascript"