如何在Javascript中拆分IPv6地址以获取网络ID子网?

huangapple go评论65阅读模式
英文:

How to split IPV6 address to get the Network ID subnet in Javascript?

问题

我有一个"broker"发现服务,它允许用户找到其产品的私有本地IP地址。该产品将其私有本地IP地址与所在网络的IPV4地址和IPV6地址一起上传到数据库。

当用户访问我的Web应用程序(discovery.example.com)时,它将获取用户的IPV4/IPV6地址(无论他们是如何连接的),然后检查数据库是否有与该IP地址匹配的条目,如果有,则将相关的私有本地IP地址返回给用户,然后用户就可以在其家庭网络中获得其产品的本地IP地址。

显然,每个设备的IPV6地址的最后几个部分都会不同,所以我想知道您如何获取IPV6地址的前四个字节(因为那是它们的网络ID)?

假设我得到了这个地址(这是随机生成的,请不要试图搜索它,因为它将指向无处):

7g98:i9e:k897:a388:908a:j983:d7h7:98o0

我想将它拆分成只有:

7g98:i9e:k897:a388

这样,无论他们在哪个设备上进行检查,它仍然知道它们位于同一网络?

谢谢。

英文:

I have this 'broker' discovery service, where it allows the user to find what the private local IP address of their product is. This product uploads it's private local IP address along with the IPV4 address and IPV6 address of the network it's on to a database.

When this user reaches to my web app (discovery.example.com), it will get either the user's IPV4/IPV6 address (whatever way they connect through) and check the database if there are any matches with that IP address, if there are then return the associated private local IP address to the user, then the user has their local IP address of their product in their home network.

Obviously each IPV6 address from each device will be different at the ending parts, so I was wondering on how you would get the first four bytes of data of an IPV6 address (as that's their network ID)?

Say I got this for an address (this is randomly made, don't try searching it up as it'll lead to nowhere):

7g98:i9e:k897:a388:908a:j983:d7h7:98o0

I want to split it up so I only get:

7g98:i9e:k897:a388

So whatever device they check on, it still knows its the same network?

Thanks.

答案1

得分: 1

以下是您想要的内容:

const ip = "7g98:i9e:k897:a388:908a:j983:d7h7:98o0";

const match = ip.match(/((.*?):){4}/)
if (match) {
    console.log(match[0].slice(0,-1))
}
英文:

Here is what you want:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const ip = &quot;7g98:i9e:k897:a388:908a:j983:d7h7:98o0&quot;;

const match = ip.match(/((.*?):){4}/)
if (match) {
    console.log(match[0].slice(0,-1))
}

<!-- end snippet -->

huangapple
  • 本文由 发表于 2020年7月22日 22:21:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/63036467.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定