Scene:
According to the IP address to determine the location of the user, although there are many articles on the internet, but I recorded a look on the understanding, do not have to look at the long text to understand their own.
We have a correspondence between the city and the IP address segment, such as:
Shanghai: 202.127.0.0 ~ 202.127.4.255
Beijing: 122.200.64.0 ~ 122.207.255.255
At this point, if the user's IP address is 122.202.2.0, we will be able to know his address in Beijing based on this table.
Method:
Use an ordered set to record this table, each city stores two data, one is the city name corresponding to the score for the maximum IP address. The other one is "#" plus the city name corresponding to the minimum IP address of the score.
Analysis:
Take the last previous fractional value that is greater than the current IP, if the value is # Start, the description is the smallest IP of a city, that is, the current IP is not in any city range, if not the # start, then the IP belongs to the city.
|----Shanghai Maximum IP (80=>sh)|----Shanghai min IP (50=>#sh)|----Beijing largest IP (30=>bj)|---- Beijing min IP (20=>#BJ)
Code implementation:
//First Use Ip2long to convert IP address to corresponding decimal number, here in order to facilitate the direct use of virtual digital representation$redis->zadd (' Zset ', ' #bj ');//minimum IP plus #$redis->zadd (' Zset ', +, ' BJ ');$redis->zadd (' Zset ', ' #sh ');//minimum IP plus #$redis->zadd (' zset ', ' sh ');//get the city that corresponds to the IP$cityIp= 34;$b=$redis->zrangebyscore (' Zset ',$cityIp, ' +inf ',Array(' limit ' = =Array(0,1) )); if($b) { if(Strpos($b[0], ' # ') = = = 0) { Echo' The city is not '; } Else { Echo' City is ',Print_r($b); } } Else { Echo' The city does not exist ';}
Redis Tips--ip address lookup for cities