1

I need to calculate the netmask given a Start and End ip address for a block in a subnet, in javascript. I leveraged this answer https://stackoverflow.com/a/8872819/664479 and

With a startAddress of ac164980 and endAddress of ac16498e

var scope = ipScope;
var s = parseInt("0x"+startAddress ,16);
var e = parseInt("0x"+endAddress ,16);
var m = parseInt("0xFFFFFFFF",16);

var nm = ""+(m ^ s ^ e);

I expected FFFFFFC0 but got -15

Where'd I go wrong?

Community
  • 1
  • 1
Stuart Siegler
  • 1,686
  • 4
  • 30
  • 38
  • For a start you didn't convert your integers back to hexadecimal at the end. –  Feb 05 '15 at 19:32

2 Answers2

0

You need to convert the result back to hexadecimal string at the end (decimalToHexString function taken from: https://stackoverflow.com/a/697841/932282):

function decimalToHexString(number)
{
    if (number < 0)
    {
        number = 0x100000000 + number;
    }
    return number.toString(16).toUpperCase();
}

var startAddress = "ac164980",
    endAddress = "ac16498e";

var s = parseInt("0x"+startAddress, 16);
var e = parseInt("0x"+endAddress, 16);
var m = parseInt("0xFFFFFFFF", 16);

var nm = decimalToHexString(m ^ s ^ e);

The result is FFFFFFF1 however.

Community
  • 1
  • 1
mhu
  • 17,720
  • 10
  • 62
  • 93
0

There are actually 2 problems here. The first is the calculation assumption using startIP and endIP.

It really should be the scopeSize of the subnet that the startIP and endIP lie within.

The second is the representation of the negative value that's returned. That's Fixed with:

var nm = (0xFFFFFFFF + (-1 ^(scope-1)) +1).toString(16).toUpperCase();
Stuart Siegler
  • 1,686
  • 4
  • 30
  • 38