简体   繁体   中英

Derive Netmask given start and end IP addresses

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?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM