Saturday, February 5, 2011

Looping an IP Address Range

As a Security/Systems Administrator, one of my task is to scan for rouge devices, services and other status and/or information regarding our network. One of the major task is to know which hosts belongs to a specified IP Range for example 192.168.0.1 to 192.168.100.255.

One of the best solutions and probably the fastest is to convert the Ip range and iterate in its Binary form. With the help of shift operators (<< and >>), & and | operator here is my simple implementation in C# =)

-----------------------------------------------------------------
int counter;

int[] ipStart = {192,168,0,0};
int[] ipEnd = {192,168,255,255};

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

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

for (counter = startIP; counter <= endIP; counter++)
{
Console.WriteLine("{0}.{1}.{2}.{3}",
(counter & 0xFF000000) >> 24,
(counter & 0x00FF0000) >> 16,
(counter & 0x0000FF00) >> 8,
counter & 0x000000FF);
}
-------------------------------------------------------------------------

0xFF000000 is equal to 11111111000000000000000000000000 in Binary
0x00FF0000 is equal to 00000000111111110000000000000000 in Binary
0x0000FF00 is equal to 00000000000000001111111100000000 in Binary
0x000000FF is equal to 00000000000000000000000011111111 in Binary


Till Next Time.......