Converting maximum host addresses to CIDR netmask

1

I am trying to convert a numeric value of maximum usable host address' to a CIDR notation IP, for example: 192.168.1.1/28 has a usable host space of 14. However 192.168.1.1/30 and /31 both have a usable host space of 2 which is where the problem comes into play. The below code shows expected and actual values:

    let ip = "192.168.1.1";

    console.log("max hosts of 14, expected: 255.255.255.240, got: " + test(ip, 14));
        //the problem, these should give the correct result respectively
        console.log("max hosts of 2, expected: 255.255.255.254, got: " + test(ip, 2));
        console.log("max hosts of 2, expected: 255.255.255.252, got: " + test(ip, 2));

    let test = function(ip, maxHosts){
        let numericNetmask = (maxHosts ^ 0xFFFFFFFF) - 1;
        let str = [];
        for (let shift = 24; shift > 0; shift -= 8) {
            str.push(((numericNetmask >>> shift) & 0xFF).toString());
        }
        str.push((numericNetmask & 0xFF).toString());
        return str.join(".");
    };

now of course I understand that it would be impossible to convert maximum hosts on it's own back to the netmask in this case, however, is this possible given the IP address? (note: this is classess supernetting).

Of course in a normal use case, for example a form this could be "hacked" by having the CIDR netmask stored as the value, but i was hoping for an alternative.

javascript
ipv4
cidr
netmask
asked on Stack Overflow Dec 8, 2018 by jordan t

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0