Counting the number of IP addresses present between two IP addresses in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in two IPv4 addresses, and returns the number of addresses between them (including the first one, excluding the last one).

This can be done by converting them to decimal and finding their absolute difference.

Example

Following is the code −

 Live Demo

const ip1 = '20.0.0.10';
const ip2 = '20.0.1.0';
const countIp = (ip1, ip2) => {
   let diff = 0;
   const aIp1 = ip1.split(".");
   const aIp2 = ip2.split(".");
   if (aIp1.length !== 4 || aIp2.length !== 4) {
      return "Invalid IPs: incorrect format";
   }
   for (x = 0; x < 4; x++) {
      if (
         isNaN(aIp1[x]) || isNaN(aIp2[x])
         || aIp1[x] < 0 || aIp1[x] > 255
         || aIp2[x] < 0 || aIp2[x] > 255
      ) {
         return "Invalid IPs: incorrect values"
      }
      diff += (aIp1[x] - aIp2[x]) * (256 * (3-x));
   }
   return Math.abs(diff);
};
console.log(countIp(ip1, ip2));

Output

Following is the console output −

256
raja
Published on 20-Apr-2021 06:41:10
Advertisements