calculate IP range using PHP and CIDR

greentiger picture greentiger · Apr 12, 2013 · Viewed 18.7k times · Source

I've seen various questions and answers around this site and I'm still having difficulty wrapping my head around this problem (could be because I've got a cold). Regardless, I'm trying to come up with a small web app that will create tables of IP addresses for each of our offices.

Like say if I create a new scope for 10.1.10.0/4 it will create an array (which I can then print to a table) of:

 10.1.10.0 network ID
 10.1.10.1 gateway
 10.1.10.2 usable
 10.1.10.3 broadcast

(not that it would insert the descriptions automatically but that's what we'd be doing).

I'm pretty sure I'm going to be using ip2long/long2ip to store the addresses as integers but still.

Answer

user149341 picture user149341 · Apr 16, 2013

As you've already noted, all IPv4 addresses can be converted to numbers using ip2long(), and converted back using long2ip(). The critical extra bit I'm not sure you've noticed is that sequential IPs correspond with sequential numbers, so you can manipulate these numbers!

Given a CIDR prefix (e.g, $prefix = 30 for your range), you can calculate the number of IPs in that range using a bit shift operator:

$ip_count = 1 << (32 - $prefix);

And then loop through all the IPs in that range using:

$start = ip2long($start_ip);
for ($i = 0; $i < $ip_count; $i++) {
    $ip = long2ip($start + $i);
    // do stuff with $ip...
}