php判断用户ip是否在同一网段或同一局域网实例
原理根据用户给出的ip,再获取当前IP然后转换成数字型的,根据IP,a,b,c类进行计算,根据进行对比就OK,代码如下:
- $start =ipToInt('192.168.1.110');
- $end = ipToInt('192.168.0.1');
- $ipInt = ipToInt( get() );
- $result = false;
- if ($ipInt>=$start && $ipInt<=$end) {
- $result = true;
- }
- if( $result )
- {
- echo '在同一网段';
- }
- else
- {//开源代码phpfensi.com
- echo '不在同一网段';
- }
- //不在同一网段
- /*
- * IP转成整形数值
- * @param string $ip IP
- * @return int
- */
- function ipToInt($ip) {
- $ips教程 = explode('.',$ip);
- if (count($ips)>=4) {
- $int = $ips[0]*256*256*256+$ips[1]*256*256+$ips[2]*256+$ips[3];//根据IP,a,b,c类进行计算
- } else {
- throw new Exception('ip is error');
- }
- return $int;
- }
- /*
- * 获取用户IP地址 192.68.0.110
- */
- function get() {
- if ($_SERVER['HTTP_CLIENT_IP'] && $_SERVER['HTTP_CLIENT_IP']!='unknown') {
- $ip = $_SERVER['HTTP_CLIENT_IP'];
- } elseif ($_SERVER['HTTP_X_FORWARDED_FOR'] && $_SERVER['HTTP_X_FORWARDED_FOR']!='unknown') {
- $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
- } else {
- $ip = $_SERVER['REMOTE_ADDR'];
- }
- return $ip;
- }