Search code examples
ipcounterincrement

How to increment IP address


How to increment an IP address like this:

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
...

My attempt gets me the first two tail nodes correctly, but anything more than that it gives the wrong output.

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
}

Solution

  • Instead of modelling an IP address as an array, model it as a single number.

    Each octet can be extracted by a mask and shift.

    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]