给定一个范围列表,我们如何查找给定值是否存在于节点js的该范围列表中 [英] Given a list of ranges how can we find if the given value exist in that list of ranges in node js

查看:106
本文介绍了给定一个范围列表,我们如何查找给定值是否存在于节点js的该范围列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组ip范围,我需要确定用户给定的ip是否存在于给定的ip范围列表之间.

I have aset of ip ranges and i need to find if the ip given by the user exists between the given list of ip ranges .

这是该问题的延续

乔纳斯(Jonas)帮助我获取了该IP是否存在.但是我不想进行详尽的迭代搜索,我想进行快速的性能密集型搜索,因为我的IP范围(或数字范围)列表非常庞大.

Jonas helped me get the ip exists or not. But i donot want to do a exhaustive iterative search , I want to go a fast performance intensive search as my list of ip ranges (or number ranges) will be huge.

我按照乔纳斯的观点研究了布隆过滤器,但我不相信布隆过滤器可能会有所帮助.我也在看间隔树但我不认为它可以搜索间隔以间隔作为输入.

I looked into bloom filters as pointed by jonas but i am not convinced bloom filter might help . Also i was looking at Interval Tree But i dnt think it can search interval it takes intervals as inputs.

我的IP列表范围为 https://github.com/client9/ipcat/blob/master/datacenters.csv#L4

如何快速搜索它.我正在使用节点js

How to search it in a fast manner . I am using node js

推荐答案

我发现您的许多ip看起来像这样:

Ive observated that many of your ips look like this:

123.123.123.0 - 123.123.123.255

因此要过滤掉它们,我们只需要阻止以以下内容开头的每个ip:

So to filter them out, we just need to block every ip starting with:

123.123.123

现在只剩下16E6 ip范围可被阻止.但是,您可能只阻止其中的一些,这使我们能够将其存储在Set中.一点代码:

Now there are just 16E6 ip ranges left for being blocked. However you will probably block just a few of them, which gives us the ability to store that in a Set. A bit of code:

const blockedRange = new Set();

function IPtoBlock(ip){
   return ip.split(".").slice(0,3).join(".");
}

//to block an ip range ( if youve got one ip of it):
blockedRange.add( IPtoBlock("192.168.2.48") );

//to check for an ip
blockedRange.has( IPtoBlock( someip ));


因此,现在只有一些范围不是块,例如:


So now there are just a few ranges that are not a block, like:

 5.44.26.144 - 5.44.26.159

但是,嘿,只有15个ips,我们可以通过ip列表将其添加到禁令中:

But hey, just 15 ips, which we can add to a ban by ip list:

const blockedIPs = new Set();

function NumtoIP(num){
  return (num+"").split("").reduce((res,char,i) =>
    res + (!i || i%3?"":".") + (char === "0"?"":char)
  ,"");
 }

function addRange(start,end){
 start = IPtoNum(start);
 end = IPtoNum(end);//include from last answer
 for(var i = start; i <= end; i++){
   blockedIPs.add( NumtoIP( i ) );
 }
}


因此,当遍历我们的范围列表时,我们可以分开:


So when iterating over our range list we can seperate:

ranges.forEach(([min,max]) => {
  if( min.substr(-1) === "0" && max.substr(-3) === "255" ){
      blockedRange.add( IPtoBlock( min ) );
  }else{
      addRange(min, max);
  }
});

要检查IP是否通过检查

To check if an ip fails the check

function isBlocked(ip){
  return blockedIPs.has(ip) && blockedRange.has( IPtoBlock(ip) );
 }

这篇关于给定一个范围列表,我们如何查找给定值是否存在于节点js的该范围列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆