zoukankan      html  css  js  c++  java
  • How to detect visitor’s country using his IP address-根据IP地址转换成国家

    http://de77.com/php/how-to-detect-visitors-country-using-his-ip-address

    关键知识点:

    1,IP地址转换成10进制计算公式

       1.2.3.4 = 4 + (3 * 256) + (2 * 256 * 256) + (1 * 256 * 256 * 256)

      14.155.114.41 =  41 + (114 * 256) + (155 * 256 * 256) + (14 * 256 * 256 * 256) = 245068329

       也可直接通过http://whatismyipaddress.com/ip/14.155.114.41计算

    问题:

    针对HK的固定IP能正确得出结果,而动态IP有时无法得出结果。如上面的14.155.114.41为一次实际的动态IP,它无法得出是大陆IP。

    经过分析,解析不出来原因如下:

    IpToCountry.csv 数据没有问题,根据245068329前三位245,查找245.php找不到记录,因为数据保存在244.php中

    解决方法,修改Ip2Country.php,load函数为:

    public function load($ip)
    	{
    		$ip = floatval($this->ip2int($ip));
    
    		$piece = substr($ip, 0, 3);
    //		echo($ip);
    		$this->parseByPiece($piece, $ip);	// first parse
    
    		if ( $this->property['countryCode'] == '' )	
    		{
    			$piece = floatval($piece) - 1;
    			$this->parseByPiece($piece, $ip);	// second parse
    		}
    
    		if ( $this->property['countryCode'] == '' )
    		{
    			$this->property['countryCode'] = '?';
    			$this->property['country'] = '?';
    		}
    		
    		return $this;
    	}
    
    	private function parseByPiece($piece, $ip)
    	{
    		if (!file_exists($this->dir . $piece . '.php'))
    		{
    			$this->property['countryCode'] = '?';
    			$this->property['country'] = '?';
    			return $this;	
    		}
    		
    		include $this->dir . $piece . '.php';
    		
    		foreach ($entries AS $e)
    		{	
    			$e[0] = floatval($e[0]);
    			if ($e[0] <= $ip and $e[1] >= $ip)
    			{
    				$this->property['countryCode'] = $e[2];
    				$this->property['country'] = $this->codes[$e[2]];
    				return $this;
    			}
    		}
    	}
    

      

  • 相关阅读:
    简历的快速复制
    使用stringstream对象简化类型转换
    猴子吃桃
    new和delete运算符
    绘制正余弦曲线
    计算学生的平均成绩
    判断是否为回文字符串
    统计各种字符个数
    验证用户名
    回溯法(挑战编程)
  • 原文地址:https://www.cnblogs.com/season2009/p/2577325.html
Copyright © 2011-2022 走看看