Dec 28

Here's a quick function I wrote to generate IP address ranges using recursion.

function iprange($oct, $prefix=""){
	for($i=1;$i<256;$i++){
		if($oct == 1) print("$prefix.$i\\n");
		else iprange($oct - 1, "$prefix.$i");
	}
}

Just call it with the number of octets you want to generate and the beginning of the IP range.

Example:

iprange(2, "127.0");

Output:

127.0.1.1
127.0.1.2
127.0.1.3
127.0.1.4
127.0.1.5

127.0.255.254
127.0.255.255

Enjoy :)

  • Digg
  • StumbleUpon
  • del.icio.us
  • Reddit

5 Responses

  1. G-Brain Says:

    Nice. But what about 127.0.0.1, and you could certainly make that $oct thing easier…

    My take:

    function iprange($prefix){
    $dots = substr_count($prefix,".");
    if ($dots == 3) echo($prefix);
    else {
    $oct = (3 - $dots);
    if ($oct == 1) $i = 1;
    else $i = 0;
    for($i;$i<=255;$i++){
    if($oct == 1) echo("$prefix.$i\n");
    else iprange("$prefix.$i");
    }
    }
    }

    iprange("127.0");

  2. admin Says:

    I like my 4-line function better, but yeah yours is nice too :P

  3. disruptiv Says:

    are you some kind of homo or something fish

  4. admin Says:

    I don't know, you're the one reading my BLOG, fag.

  5. Stephen Paulger Says:

    This is essentially the same code as in your dictionary generating function.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.