Re: How to ask "if private IP"?
| From: | Jochem Maas | Date: | Mon, 26 Nov 2007 11:43:45 +0000 |
| Subject: | Re: How to ask "if private IP"? | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-265021@lists.php.net to get a copy of this message | ||
Ronald Wiplinger wrote:
> I use $aa=$_SERVER["REMOTE_ADDR"];
>
> and
>
> if(($aa=="192.168.2.108") || ($aa=="192.168.2.34")) {
> $aa="61.64.101.101"; // for testing put in a public IP
> }
>
>
> However, I would like to cover all private IPs (192.168.x.x and 10.x.x.x
> and 172.??.x.x). How can I do that simple?
probably not the best or fastest way to do it but here is what I use:
function isPrivateIP($theip)
{
foreach (array("10.0.0.0/8",
"172.16.0.0/12",
"192.168.0.0/16") as $subnet)
{
list($net, $mask) = explode('/', $subnet);
if(isIPInSubnet($theip, $net, $mask))
return true;
}
return false;
}
function isIPInSubnet($ip, $net, $mask)
{
$firstpart = substr(str_pad(decbin(ip2long($net)), 32, "0", STR_PAD_LEFT) ,0 ,
$mask);
$firstip = substr(str_pad(decbin(ip2long($ip)), 32, "0", STR_PAD_LEFT), 0, $mask);
return (strcmp($firstpart, $firstip) == 0);
}
>
> bye
>
> Ronald
>