2011-08-17 167 views
0

如何比较本地IP地址范围到公有IP地址在PHP?如何比较一个本地IP地址范围到公共IP地址在PHP?

我想比较我的IP地址是否在范围内。 如果它不在范围内,我想回显“失败连接”?

+0

请定义“in rang”。 –

+0

你的意思是范围? – jman

+0

请定义“范围内”。是什么让一个IP在另一个范围内?你指的是哪个“本地IP”,127.0.0.1?您的路由器分配的IP?服务器的公共互联网IP? –

回答

0
$ipRanges = array(
    array('10.1.1.1' , '10.1.10.255') , 
    array('192.168.12.1' , '192.168.12.16') 
); 


$theIP = '10.1.5.5'; # Could be $_SERVER['REMOTE_ADDR'] for accessing IP address 


$theIPdec = ip2long($theIP); # Converts from an IP address to an integer 
$inRange = false; 
foreach($ipRanges as $r){ 
    if($theIPdec >= ip2long($r[0]) 
     && $theIPdec <= ip2long($r[1])){ 
    # IP is in this range 
    $inRange = true; 
    break; 
    } 
} 


if(!$inRange){ 
# No Matches to Ranges 
    echo 'fail connected'; 
}