Skip to content Skip to sidebar Skip to footer

Split An IP Address Into Octets, Then Do Some Math On Each Of The Octets

I actually have this working, but its very ugly, and its keeping me awake at night trying to come up with an eloquent piece of code to accomplish it. I need to take a series of str

Solution 1:

There you go:

var ips = ["1.2.3.4", "2.3.4-6.7", "1.2.3.4-12"];
for(var i=0; i<ips.length; i++) {
    var num = 1;
    var ip = ips[i];
    var parts = ip.split('.');
    for(var j=0; j<parts.length; j++) {
        var part = parts[j];
        if(/-/.test(part)) {
            var range = part.split('-');
            num *= parseInt(range[1]) - parseInt(range[0]) + 1;
        }
    }
    alert(ip + " has " + num + " ips.");
}​

This code also handles ranges like 1.2.3-4.0-255 correctly (i.e. 256*2=512 ips in that range). The list items that have no ranges yield a total of 1 ips, and you can ignore them based on the resulting num if you don't need them.

You'll probably need to slightly modify my example, but I'm confident you won't have any trouble in doing so.


Solution 2:

Ok, this is how I would do it

var addr = '1.1.3-10.4-6';

function getNumAddresses(input) {
    var chunks = input.split('.');
    var result = 1;

    for (var i = 0; i < 4; i++) {
        if (chunks[i].indexOf('-') != -1) {
            var range = chunks[i].split('-');
            result *= parseInt(range[1]) -  parseInt(range[0]) + 1;
        }
    }

    return result;
}

alert(getNumAddresses(addr));

Post a Comment for "Split An IP Address Into Octets, Then Do Some Math On Each Of The Octets"