如果有人已經很難找到上述代碼,由@Uffe建議,我已將它列入如下:
<?php
/**
* Check if a client IP is in our Server subnet
*
* @param string $client_ip
* @param string $server_ip
* @return boolean
*/
function clientInSameSubnet($client_ip=false,$server_ip=false) {
if (!$client_ip)
$client_ip = $_SERVER['REMOTE_ADDR'];
if (!$server_ip)
$server_ip = $_SERVER['SERVER_ADDR'];
// Extract broadcast and netmask from ifconfig
if (!($p = popen("ifconfig","r"))) return false;
$out = "";
while(!feof($p))
$out .= fread($p,1024);
fclose($p);
// This is to avoid wrapping.
$match = "/^.*".$server_ip;
$match .= ".*Bcast:(\d{1,3}\.\d{1,3}i\.\d{1,3}\.\d{1,3}).*";
$match .= "Mask:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/im";
if (!preg_match($match,$out,$regs))
return false;
$bcast = ip2long($regs[1]);
$smask = ip2long($regs[2]);
$ipadr = ip2long($client_ip);
$nmask = $bcast & $smask;
return (($ipadr & $smask) == ($nmask & $smask));
}
在這裏,你限制自己的IPv4。現在,這還不夠。你應該 a)對IPv6也很熟悉,並且 b)定義什麼是「本地」的定義列表:真的只有192.168。*?如果你在一個擁有自己IP的網絡中呢?或在一個10. *網絡? – glglgl
可能重複的[如何知道IP是否是外部的?](http://stackoverflow.com/questions/14125735/how-to-know-if-an-ip-is-external-or-not) – user956584