简体   繁体   English

找出单个 IP (v4/v6) 地址的 CIDR (TypeScript)

[英]Finding out CIDR for a single IP (v4/v6) Address (TypeScript)

I`m working on a project using TypeScript and have access to a key-value based storage.我正在使用 TypeScript 处理一个项目,并且可以访问基于键值的存储。 The requirement is to find data related to a single IP (match key).要求是查找与单个 IP(匹配键)相关的数据。

Unfortunately the key is always a CIDR covering a lot of IP's (to save storage due to many records).不幸的是,关键始终是一个覆盖大量 IP 的 CIDR(由于许多记录而节省存储空间)。 During my tests I was unable to find the correct CIDR belonging to a specific IP.在我的测试中,我无法找到属于特定 IP 的正确 CIDR。

Example data:示例数据:

"103.21.244.0/24" - "data, lorem ipsum, etc"

Example IP to find:要查找的示例 IP:

"103.21.244.1"

I have tested several libraries like: ip-address , ip-num , ip-to-int , ipaddr.js and more, but I am unable to get the result I want.我已经测试了几个库,如: ip-addressip-numip-to-intipaddr.js等等,但我无法得到我想要的结果。

Maybe I am just being dumb and do not understand the IP specification correctly, or maybe I am just misusing these libraries, please enlighten me.也许我只是愚蠢,没有正确理解 IP 规范,或者我只是滥用了这些库,请赐教。

Surely there has to be a way without calling external API's (like RIPE) and without having to store billions of IP's instead of their CIDR.当然,必须有一种方法无需调用外部 API(如 RIPE),也无需存储数十亿个 IP 而不是它们的 CIDR。

Essentially the requirement is quite simple: "find this KEY (in CIDR) by this IP (v4 or v6)".基本上要求很简单:“通过这个 IP(v4 或 v6)找到这个 KEY(在 CIDR 中)”。

Any help, advice, example solutions are highly appreciated.任何帮助、建议、示例解决方案都受到高度赞赏。

IP address can be converted to a single number. IP 地址可以转换为单个数字。 The abcd form is a just base-256 representation of a 32-bit number. abcd形式只是 32 位数字的 base-256 表示。 Convert both the address and the subnet mask to integer.将地址和子网掩码都转换为整数。 Then use "bitwise and" operation to apply the mask to the target IP addresses and compare with the network address.然后使用“按位与”操作将掩码应用到目标IP 地址并与网络地址进行比较。

 function addrToNumber(addr) { return addr.split(".").reduce((acc,cur,i)=> acc += (Number(cur) << ( (3-i) * 8) ) ,0) } function subnetMaskToNumber(mask) { return (0xffffffff << (32 - Number(mask))) & 0xffffffff; } const cidr = "103.21.244.0/24"; const [networkAddr,subnetMask] = cidr.split("/"); const ipAddr = "103.21.244.1"; const match = (addrToNumber(ipAddr) & subnetMaskToNumber(subnetMask)) == addrToNumber(networkAddr) console.log(match);

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

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