JavaScript:这些子网中的IP是什么? [英] JavaScript: Is IP In One Of These Subnets?
问题描述
所以我有~12600个子网:
So I have ~12600 subnets:
例如。 123.123.208.0/20
eg. 123.123.208.0/20
和一个IP。
我可以使用SQLite数据库或数组或其他
I can use a SQLite Database or an array or whatever
一个月前有一个类似的问题,但是我不是要针对一个子网检查一个IP而是一堆子网(显然是最有效的方式,希望不是O(总子网)):)
There was a similar question asked about a month ago, however I am not looking for checking one IP against one subnet but a bunch of subnets (obviously the most efficient way, hopefully not O(total subnets)) :)
如何检查IP是否属于这些子网之一,我需要是真的还是假的,不是子网的这有助于优化。
How can I check that the IP is one of in one of these subnets, I need true or false not the subnet if that helps optimisation.
当前列表中有类似的子网,例如:
(实际提取)
There are similar subnets in the current list eg.: (actual extract)
123.123.48.0/22 <-- not a typo
123.123.48.0/24 <-- not a typo
123.123.90.0/24
123.123.91.0/24
123.123.217.0/24
总计他们的范围从4.xyz到222.xyz
In total they range from 4.x.y.z to 222.x.y.z
推荐答案
最好的方法是IMO使用按位运算符。例如, 123.123.48.0/22
表示(123 << 24)+(123 << 16)+(48 << 8 )+ 0
(= 2071670784;这可能是负数)作为32位数字IP地址, -1<<(32-22)
= -1024作为面具。有了这个,同样,您的测试IP地址转换为数字,您可以这样做:
The best approach is IMO making use of bitwise operators. For example, 123.123.48.0/22
represents (123<<24)+(123<<16)+(48<<8)+0
(=2071670784; this might be a negative number) as a 32 bit numeric IP address, and -1<<(32-22)
= -1024 as a mask. With this, and likewise, your test IP address converted to a number, you can do:
(inputIP & testMask) == testIP
例如,123.123.49.123在此范围内,如 2071671163 &安培; -1024
是2071670784
For example, 123.123.49.123 is in that range, as 2071671163 & -1024
is 2071670784
所以,这里有一些工具函数:
So, here are some tool functions:
function IPnumber(IPaddress) {
var ip = IPaddress.match(/^(\d+)\.(\d+)\.(\d+)\.(\d+)$/);
if(ip) {
return (+ip[1]<<24) + (+ip[2]<<16) + (+ip[3]<<8) + (+ip[4]);
}
// else ... ?
return null;
}
function IPmask(maskSize) {
return -1<<(32-maskSize)
}
测试:
(IPnumber('123.123.49.123') & IPmask('22')) == IPnumber('123.123.48.0')
yield true
。
如果你的面具格式为'255.255.252.0',那么你可以使用掩码的IPnumber函数也是。
In case your mask is in the format '255.255.252.0', then you can use the IPnumber function for the mask, too.
这篇关于JavaScript:这些子网中的IP是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!