INFOSYS
INFOSYS

Reputation: 1585

How to check if a given ip falls between a given ip range using node js

Please pardon for this trival question

Given a set of Ip the set is quite large and might increase https://github.com/client9/ipcat/blob/master/datacenters.csv#L4

Small example set - first column start ip second - end ip range

enter image description here

I will get the user ip from the request . I need to check if the ip falls in these set of ranges . How do i accomplish this.

I have looked into ip_range_check and range_check.

But they donot check for a ip given given range . How is thhis possible in node js with utmost performance. I dont want to go for a exhaustive search as performance is a hight priority.

Please help something new and quite challenging so far to me.

Upvotes: 14

Views: 23081

Answers (3)

pyBlob
pyBlob

Reputation: 153

Starting with Node.js v15, we can also use BlockList from the native net package: https://nodejs.org/api/net.html#class-netblocklist

We can create the BlockList object, populate it with the relevant entries from the table:

import { BlockList } from "net"

const blockList = new BlockList()
blockList.addAddress("123.123.123.123")
blockList.addRange("10.0.0.1", "10.0.0.10")
blockList.addSubnet("8592:757c:efae:4e45::", 64, "ipv6")

and test if the list matches individual addresses:

console.log(blockList.check('123.123.123.123'));  // Prints: true
console.log(blockList.check('10.0.0.3'));  // Prints: true
console.log(blockList.check('222.111.111.222'));  // Prints: false

// IPv6 notation for IPv4 addresses works:
console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true
console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true

Upvotes: 14

Jonas Wilms
Jonas Wilms

Reputation: 138277

This is quite easy if we convert the ips to simple numbers:

function IPtoNum(ip){
  return Number(
    ip.split(".")
      .map(d => ("000"+d).substr(-3) )
      .join("")
  );
}

Then we can check a certain range as:

 if( IPtoNum(min) < IPtoNum(val) &&    IPtoNum(max) > IPtoNum(val) ) alert("in range");

That can also be applied to a table:

const ranges = [
  ["..41", "192.168.45"],
  ["123.124.125"," 126.124.123"]
];

const ip = "125.12.125";
const inRange = ranges.some(
  ([min,max]) => IPtoNum(min) < IPtoNum(ip) &&   IPtoNum(max) > IPtoNum(ip)
);

Upvotes: 34

Deja
Deja

Reputation: 356

//Use getCIDR from rangecalc
getCIDR("5.9.0.0", "5.9.255.255")
//This return 5.9.0.0/16

//You can then use ipRangeCheck from ip_range_check
ipRangeCheck("IP TO BE CHECKED", "5.9.0.0/16")
//returns true or false

Pretty sure there's other way to do this.

Upvotes: 9

Related Questions