views:

75

answers:

2

Hi, I know I can do this easily by converting the IP addresses to decimal notation first using PHP built in functions like up2long and long2ip. I just want to be able to do the same using the standard IP address notation as an exercise.

The problem I am thinking goes like this: Given an starting IP address, say 192.168.1.100, and an ending IP address, say 201.130.22.10. Make the program that prints all the address numbers in that range (192.168.1.100, 192.168.1.101, … , 201.130.22.9, 201.130.22.10).

I was thinking that maybe the way to go would be to make a nested for loop inside a while condition until the first octet of the starting address matches the first octet of the ending address. Then execute the same block of code for the second octet and so on until the program reaches the ending address and finished.

I just started learning to program recently so it is quite possible that my of thinking and or writing code is far from elegant. If you were to this, how would you do it?

+4  A: 

Something like this:

<?php

// works only for valid range
$start_ip = '10.0.0.1';
$end_ip = '10.0.20.1';

$start_arr = explode('.',$start_ip);
$end_arr = explode('.',$end_ip);

while($start_arr <= $end_arr)
{
    echo implode('.',$start_arr) . '<br>';

    $start_arr[3]++;
    if($start_arr[3] == 256)
    {
     $start_arr[3] = 0;
     $start_arr[2]++;
     if($start_arr[2] == 256)
     {
      $start_arr[2] = 0;
      $start_arr[1]++;
      if($start_arr[1] == 256)
      {
       $start_arr[1] = 0;
       $start_arr[0]++;
      }
     }
    }
}

?>
codaddict
Yes!!! Thanks!!!! it works and I think it is more efficient than the code I was thinhave been writing some code for this but since I was away form the computer I just used pen and paper. Will give it a ago and post it when I have mine. Your script works like a charm, thanks again.
alexis
Always a pleasure :) .Sure, do post your code when ready. Cheers !!!
codaddict
A: 

@ Gumbo and the user who commnented his reply (sorry forgot your username) Yes, that's right I want to avoid using ip2long and long2ip functions. I know in an actual program I would do it that way, I am just making this exercise to learn a little bit more. BTW I also wonder, would ip2long and long2ip be faster or slower than writing all the code without using these functions. Anyway, thanks a lot for the replies

alexis
Considering the time it'll take to write that code without using ip2long and long2ip, I would definitly use those two -- they'll make things so much easier ^^
Pascal MARTIN
Yes I know know, but there is something in my mind, it just won't let go. It is like a riddle and you know you won't rest until you know the answer ^^
alexis
+1 @alexis for taking the longer route in order to learn more :-)
richsage
thanks for the thumbs up
alexis