如何将一系列本地IP地址与php中的公共IP地址进行比较?

时间:2011-08-17 04:53:26

标签: php

如何在php中比较一系列本地IP地址与公共IP地址?

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

1 个答案:

答案 0 :(得分: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';
}