简体   繁体   English

如何在JavaScript中将十六进制(缓冲区)转换为IPv6

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

I have a buffer that contains a hex representation of an IPv6 address. 我有一个缓冲区,其中包含IPv6地址的十六进制表示。 How exactly do I convert it to an actual IPv6 representation? 如何将其准确转换为实际的IPv6表示形式?

// 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. 我真的不介意使用一个简单的库,如果它提供转换功能。

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. 我不知道我是否真的回答了您的问题,但是要将字符串IP_ADDRESS_HEX转换为IPv6地址表示形式,我将使用String.slice()将IP_ADDRESS_HEX分为8组,并使用String.join()添加“:”。在这些群体之间。

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. 当然,仅当IP_ADDRESS_HEX具有精确的32个字符时,它才起作用。

If your IP_ADDRESS_HEX always has the same size, you can do the following. 如果您的IP_ADDRESS_HEX大小始终相同,则可以执行以下操作。 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. 您也可以缩短某些块,但这不是必需的,例如ffff:0000:0000:0000:0000:0000会变成ffff::但两者都是有效的。

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"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM