Lance Pollard
Lance Pollard

Reputation: 79178

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
}

Upvotes: 1

Views: 2296

Answers (2)

Erikas
Erikas

Reputation: 1086

Working Javascript function:

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];
}

Usage:

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

Upvotes: 1

Caleth
Caleth

Reputation: 62531

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]

Upvotes: 1

Related Questions