Reputation: 780
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. :-)
Upvotes: 6
Views: 9353
Reputation: 13450
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.
Upvotes: 11
Reputation: 7168
Here's a PHP solution:
<?php
$sIP1 = '192.168.0.0';
$sIP2 = '192.168.1.255';
$aIPList = array();
if ((ip2long($sIP1) !== -1) && (ip2long($sIP2) !== -1)) // As of PHP5, -1 => False
{
for ($lIP = ip2long($sIP1) ; $lIP <= ip2long($sIP2) ; $lIP++)
{
$aIPList[] = long2ip($lIP);
}
}
?>
There's a good summary of the (basic) maths involved here
Upvotes: 2
Reputation: 118128
Use the modulus operator %
. Here is a primitive example:
#include <stdio.h>
int main(void) {
int counter;
unsigned int ip[] = { 192, 168, 0, 0 };
for ( counter = 0; counter < 1000; ++counter ) {
ip[3] = ( ++ ip[3] % 256 );
if ( !ip[3] ) {
ip[2] = ( ++ ip[2] % 256 );
}
printf("%u:%u:%u:%u\n", ip[0], ip[1], ip[2], ip[3]);
}
return 0;
}
Upvotes: 1