Wednesday, July 2, 2014

Expand IP Ranges From IP Subnet Masks

I ran into a situation where I had a third party authentication system which required a list of IP addresses. This probably isn't an issue until you start dealing w/ the environments which only list IP subnet masks. I found a great site (Network and IP address calculator) by Guido Socher that took a subnet mask and displayed a IP range (first and last address). It is not very efficient if you have more than a couple. Thankfully, the calculator was implemented in javascript and I could easily create a Node.js script to handle the automation.

An interesting bit from my code was the the function that expands the IP ranges that were calculated from Guido's calculator code. Googling did not yield any algorithms, so I took a stab at it. This really feels like it should be a recursive function, but I could not think of an elegant way to implement it.
function expandIPRange(ipform) {
    var expanded = [];
    var o1 = ipform.firstadr_1;
    while (o1 <= ipform.lastadr_1) {
        var o2 = ipform.firstadr_2;
        while ((o1 < ipform.lastadr_1 && o2 <= 255) || (o1 == ipform.lastadr_1 && o2 <= ipform.lastadr_2)) {
            var o3 = ipform.firstadr_3;
            while ((o2 < ipform.lastadr_2 && o3 <= 255) || (o2 == ipform.lastadr_2 && o3 <= ipform.lastadr_3)) {
                var o4 = ipform.firstadr_4;
                while ((o3 < ipform.lastadr_3 && o4 <= 255) || (o3 == ipform.lastadr_3 && o4 <= ipform.lastadr_4)) {
                    expanded.push(util.format("%s.%s.%s.%s", o1, o2, o3, o4));
                    o4++;
                    if (o3 <= ipform.lastadr_3 && o4 > 255) {
                        o3++;
                        o4 = 0;
                    }
                }
                o3++;
                if (o2 <= ipform.lastadr_2 && o3 > 255) {
                    o2++;
                    o3 = 0;
                }
            }
            o2++
            if (o1 <= ipform.lastadr_1 && o2 > 255) {
                o1++;
                o2 = 0;
            }
        }
        o1++;
    }

    return expanded;
}
The Node.js application can be found at my GitHub project, IPSubnetMaskToIPRange. The application takes a file of IP subnet masks and outputs 2 CSV files. A CSV file containing the IP ranges calculated by the calculator and a file containing the expanded IP addresses from the calculated ranges.

No comments: