Skip to content
PHP Logo

What considerations should be made when dealing with IP addresses that end in zero when using ip2long in PHP?

When using ip2long in PHP, IP addresses that end in zero may cause unexpected results as ip2long treats them as the network address. To handle this issue, you can add a simple check to increment the IP address by 1 if it ends in zero before converting it to a long integer.

php
$ip = '192.168.1.0';
if (substr($ip, -1) == '0') {
    $ip = long2ip(ip2long($ip) + 1);
}
$ip_long = ip2long($ip);
echo $ip_long;