【问题标题】:How to increment IP address如何增加IP地址
【发布时间】:2018-12-08 12:27:01
【问题描述】:

如何像这样增加 IP 地址:

0.0.0.0
0.0.0.1
...
0.0.0.255
0.0.1.0
0.0.1.1
...
0.0.255.0
0.1.0.0
0.1.0.1
...
0.1.0.255
0.1.1.0
...
0.1.255.0
0.1.255.1
0.1.255.2
...
0.2.0.0
...

我的尝试正确地得到了前两个尾节点,但除此之外它给出了错误的输出。

function increment_ip(input) {
  var iparray = input.concat()
  var output = []
  var i = iparray.length
  var inc = false

  while (i--) {
    var count = iparray[i]
    if (count < 255) {
      output.unshift(count)
      if (!inc) {
        iparray[i] = iparray[i] + 1
        inc = true
      }
    } else {
      iparray[i] = 0
      output.unshift(0)
      if (i - 1 > -1) {
        iparray[i - 1] = iparray[i - 1] + 1
      }
    }
  }

  return output
}

【问题讨论】:

    标签: ip counter increment


    【解决方案1】:

    不要将 IP 地址建模为数组,而是将其建模为单个数字。

    每个八位字节都可以通过掩码和移位来提取。

    var ip = (input[0] << 24) | (input[1] << 16) | (input[2] << 8) | (input[3] << 0)
    ip++
    return [ip & 0xff000000 >> 24, ip & 0x00ff0000 >> 16, ip & 0x0000ff00 >>, ip & 0x000000ff]
    

    【讨论】:

    • 如果您有超过 4 个号码,例如类似于 IP 结构但有 100 个号码 1.2.3.4.5.6.7.8.....100 或者想知道这个掩码/移位模式最多可以使用多少个号码。
    • Uncaught SyntaxError: Unexpected token ',' of this code, return line :/
    • @Erikas 问题上没有语言标签。这是有效的 Python
    【解决方案2】:

    工作 Javascript 函数:

    function incrementIP(inputIP) {
        let ip = (inputIP[0] << 24) | (inputIP[1] << 16) | (inputIP[2] << 8) | (inputIP[3] << 0);
        ip++;
        return [ip >> 24 & 0xff, ip >> 16 & 0xff, ip >> 8 & 0xff, ip >> 0 & 0xff];
    }
    

    用法:

    var myIP = [192, 168, 0, 1];
    var myIncrementedIP = incrementIP(myIP);
    console.log(myIncrementedIP);
    

    【讨论】:

      猜你喜欢
      • 2011-10-08
      • 1970-01-01
      • 2023-02-22
      • 2017-03-30
      • 1970-01-01
      • 1970-01-01
      • 2012-06-06
      • 1970-01-01
      • 2010-12-03
      相关资源
      最近更新 更多