Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I loop through an IP address range?

I want to perform a set of network tasks on an IP address range. As soon as the range is getting bigger than a class c network, I fail to enumerate all hosts in the range. I want to be able to iterate through all hosts of a network with the netmask 255.255.240.0.

From: 192.168.0.100
To:   192.168.10.100

How would one approach this? It must be a pretty common task. I come from the green fields of Cocoa iPhone programming, so a C-stylish solution would be appreciated. :-)

like image 704
Monobono Avatar asked Dec 18 '22 07:12

Monobono


1 Answers

This is a piece of code that will quickly introduce you to the nuances involved in interpreting the IP Address and iterating through it.

Things get quite simple once you start looking at an IP Address as a 32-bit unsigned integer.

#include <stdio.h>
int
main (int argc, char *argv[])
{
    unsigned int iterator;
    int ipStart[]={192,168,0,100};
    int ipEnd[] = {192,168,10,100};

    unsigned int startIP= (
        ipStart[0] << 24 |
        ipStart[1] << 16 |
        ipStart[2] << 8 |
        ipStart[3]);
    unsigned int endIP= (
        ipEnd[0] << 24 |
        ipEnd[1] << 16 |
        ipEnd[2] << 8 |
        ipEnd[3]);

    for (iterator=startIP; iterator < endIP; iterator++)
    {
        printf (" %d.%d.%d.%d\n",
            (iterator & 0xFF000000)>>24,
            (iterator & 0x00FF0000)>>16,
            (iterator & 0x0000FF00)>>8,
            (iterator & 0x000000FF)
        );
    }

    return 0;
}

Just check that none of the elements for ipStart and ipEnd are greater than 255.
That will not be an IP Address and it will mess up the code too.

like image 122
nik Avatar answered Feb 28 '23 13:02

nik