PHP – How to check if an IP address is private or not
In this post, we show you how to check if an IP address is private or not with PHP.
Let’s consider the below code:
IPAddress.php
<?php
final class IPAddress
{
public static function isPrivateIPv4($ipAddress)
{
$ipParts = explode('.', $ipAddress);
switch ($ipParts[0]) {
case 10:
case 127:
return true;
case 172:
return ($ipParts[1] >= 16) && ($ipParts[1] < 32);
case 192:
return ($ipParts[1] == 168);
case 169:
return ($ipParts[1] == 254);
}
return false;
}
public static function isPrivateIPv6($ipAddress)
{
$isPrivateIPv6 = false;
$ipParts = explode(':', $ipAddress);
if (count($ipParts) > 0) {
$firstBlock = $ipParts[0];
$prefix = substr($firstBlock, 0, 2);
if ((strcasecmp($firstBlock, 'fe80') == 0)
|| (strcasecmp($firstBlock, '100') == 0)
|| ((strcasecmp($prefix, 'fc') == 0) && (strlen($firstBlock) >= 4))
|| ((strcasecmp($prefix, 'fd') == 0) && (strlen($firstBlock) >= 4))) {
$isPrivateIPv6 = true;
}
}
return $isPrivateIPv6;
}
}
In the above code, we have created IPAddress
class and implemented the following methods:
isPrivateIPv4
: method that checks if an IPv4 address is private or notisPrivateIPv6
: method that checks if an IPv6 address is private or not
Use the methods:
// test IPv4
$ipv4Address = '192.168.22.6';
if (IPAddress::isPrivateIPv4($ipv4Address)) {
echo 'This is a private IPv4';
}
// test IPv6
$ipv6Address = 'fe80:db8:a0b:12f0::1';
if (IPAddress::isPrivateIPv6($ipv6Address)) {
echo '<br>This is a private IPv6';
}
Output:
This is a private IPv4
This is a private IPv6