• Notice regarding image hosts and attachments. See here.

PHP function like Perl Net::IP

Associate
Joined
27 Jun 2006
Posts
1,473
Chaps.

I need to write a script that takes a range of IP address, say 195.45.6.7 - 195.45.6.19, and then print them out one by one.

Now in Perl, its simple to do with Net::IP module and the code below:
Code:
my $ip = new Net::IP ('195.45.6.7 - 195.45.6.19') || die;
  # Loop
  do {
      print $ip->ip(), "\n";
  } while (++$ip);

Now how would I go about that in PHP - I am stumped!

Cheers
M.
 
Don't think there's a built-in function for it, but you could use ip2long to get the numeric representation of the upper and lower bounds, and then loop over the range of numbers:

PHP:
<?php

$start = ip2long('195.45.6.7');
$end = ip2long('195.45.6.19');

if (($start > 0 && $end > 0) || ($start < 0 && $end < 0))
{
    $span = abs($end - $start);
}
else
{
    $span = pow(2, 32) - abs($end - $start);
}

for ($i = 0; $i < $span + 1; $i++)
{
    echo long2ip($start + $i) . "\n";
}

?>

The if clause there is to account for the possibility of negative IP represenations, since PHP does not support unsigned integers. Not sure how fast it'd be for large ranges though.

Edit: here it is in action:
http://codepad.org/8F8WOlxP
 
Last edited:
Back
Top Bottom