Skip to content Skip to sidebar Skip to footer

Given A List Of Ranges How Can We Find If The Given Value Exist In That List Of Ranges In Node Js

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 . This is in continuation to this question How to check if a giv

Solution 1:

Ive observated that many of your ips look like this:

123.123.123.0 - 123.123.123.255

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

123.123.123

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

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

const blockedIPs = newSet();

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

functionaddRange(start,end){
 start = IPtoNum(start);
 end = IPtoNum(end);//include from last answerfor(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);
  }
});

To check if an ip fails the check

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

Post a Comment for "Given A List Of Ranges How Can We Find If The Given Value Exist In That List Of Ranges In Node Js"