简体   繁体   中英

How to use ip start & ip end to find out location

type    ip_start    ip_end          country     state       city

ipv4    0.0.0.0     0255.255.255    US          California  Los Angeles
ipv4    1.0.0.0     1.0.0.255       AU          Queensland  Brisbane

I have a table contain ip list for country, state and city.

My question is how can I detect user's ip location from my db

If I use php $ip = $_SERVER["HTTP_CLIENT_IP"]; , HTTP_X_FORWARDED_FOR & REMOTE_ADDR $ip = $_SERVER["HTTP_CLIENT_IP"]; , HTTP_X_FORWARDED_FOR & REMOTE_ADDR to find out user's ip.

How can I use this variable to find out which country, state & city from my db?

How ip_start & ip_end work?

ex. if my ip is $ip=123.243.51.83;

How can I use this $ip to find out location from my database?

IP addresses can be converted to numbers. You can use this to find out which range the ip is in.

Using MySQL and INET_ATON :

SELECT country FROM table WHERE 
INET_ATON("123.243.51.83") BETWEEN INET_ATON(ip_start) AND INET_ATON(ip_end);

Using PHP and ip2long :

$yourIpLong = ip2long($yourIp);
if($yourIpLong > ip2long($ipStart) && $yourIpLong < ip2long($ipEnd)){
     //IP is in range $ipStart -> $ipEnd
}else{
    //IP is not in range.
}

Note that both these solutions are for IPv4.

It would be better if you store the IP addresses in an integer representation. You can use the MySql function INET_ATON for that.

In PHP you can calculate it with:

$address = '174.36.207.186';

$addressArray = explode('.', $address);

$integerIp =   ( 16777216 * $addressArray[0] )
             + (    65536 * $addressArray[1] )
             + (      256 * $addressArray[2] )
             +              $addressArray[3];

The query (if you have stored it as integer in DB ) would be:

SELECT *
FROM table
WHERE
".$integerIp." BETWEEN ip_start AND ip_end
LIMIT 1

You also can do the coversion directly in the DB like Jim answered but why let the DB do the calculation if you can precompute it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM