使用 JavaScript 統計兩個 IP 地址之間的 IP 地址數


問題

我們需要編寫一個 JavaScript 函式,該函式接收兩個 IPv4 地址,並返回它們之間的地址數(包括第一個地址,但不包括最後一個地址)。

這可以透過將它們轉換為十進位制並找到它們的絕對差來完成。

示例

以下是程式碼 −

 線上演示

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));

輸出

以下是控制檯輸出 −

256

更新於:2021 年 4 月 20 日

1K+ 瀏覽

開啟你的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.