php how to determine if ip is localhost?

214 views Asked by At

in PHP how can i determine if an IP address string is a localhost/loopback address or not? my attempt:

function isLocalhost(string $ip): bool
{
    if ($ip === "::1") {
        // IPv6 localhost (technically ::1/128 is the ipv6 loopback range, not sure how to check for that, bcmath probably)
        return true;
    }
    $long = @ip2long($ip);
    if ($long !== false && ($long >> 24) === 127) {
        // IPv4 loopback range 127.0.0.0/8
        return true;
    }
    return false;
}
1

There are 1 answers

2
Moudi On

I use a function for that:

function is_local_ip($ip) {
    if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4)) {
        $ip = ip2long($ip);
        return ($ip >> 24) === 10 || ($ip >> 20) === 2752 || ($ip >> 16) === 49320 || ($ip >> 24) === 127;
    } elseif (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_IPV6)) {
        return substr($ip, 0, 2) === 'fc' || substr($ip, 0, 3) === 'fec' || substr($ip, 0, 4) === '2001';
    }
    return false;
}
// test the above application with a local ip and a public ip
echo is_local_ip('127.0.0.1') ? 'local' : 'public';
echo "<br />";
echo is_local_ip('41.29.18.31') ? 'local' : 'public';
echo "<br />";
echo is_local_ip('2001:db8::8c28:c929:72db:49fe') ? 'local' : 'public';

You can also use regex to catch ranges

function is_local_ip($ip) {
    if (preg_match('/^((127\.)|(192\.168\.)|(10\.)|(172\.1[6-9]\.)|(172\.2[0-9]\.)|(172\.3[0-1]\.)|(::1)|(fe80::))/', $ip)) {
        return true;
    } else {
        return false;
    }
}