Skip to main content

Calculate IP Addresses using PHP

We are going to use two functions PHP networking functions ip2long() and long2ip()

ip2long() – Converts a string containing an (IPv4) Internet Protocol dotted address into a long integer.

long2ip() – Converts a long integer address into a string in (IPv4) Internet standard dotted format.

Bitwise operators are also useful when manipulating individual bits. In our case we will use << (shift left). Consider a CIDR prefix eg. /30, you can calculate number of IPs using using <<

Example to generate /32 IP addresses

$prefix=32;//your CIDR prefix
$start_ip="192.168.0.1"
$ip_count = 1 << (32 - $prefix);

$start = ip2long($start_ip);
for ($i = 0; $i < $ip_count; $i++) {
    $ip = long2ip($start + $i);
    print($ip);
}
//Result: 192.168.0.1/32

Example to generate /32 IPs from a /30

$prefix=30;//your CIDR prefix
$start_ip="192.168.0.1"
$ip_count = 1 << (32 - $prefix);

$start = ip2long($start_ip);
for ($i = 0; $i < $ip_count; $i++) {
    $ip = long2ip($start + $i);
    print($ip);
}
//Result: 192.168.0.1/32 192.168.0.2/32 192.168.0.3/32 192.168.0.4/32

Inspired by stackoverflow.