2011-08-17 83 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'; 
}