Redis Tips--ip address lookup for cities

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.