简体   繁体   English

如何使用ip start&ip end查找位置

[英]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. 我有一个表包含国家,州和城市的IP列表。

My question is how can I detect user's ip location from my db 我的问题是如何从我的数据库中检测用户的ip位置

If I use php $ip = $_SERVER["HTTP_CLIENT_IP"]; , HTTP_X_FORWARDED_FOR & REMOTE_ADDR 如果我使用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. $ip = $_SERVER["HTTP_CLIENT_IP"]; , HTTP_X_FORWARDED_FOR & REMOTE_ADDR找出用户的IP。

How can I use this variable to find out which country, state & city from my db? 如何使用此变量来查找我的数据库中的哪个国家/地区,州和城市?

How ip_start & ip_end work? ip_start和ip_end如何工作?

ex. 恩。 if my ip is $ip=123.243.51.83; 如果我的IP是$ip=123.243.51.83;

How can I use this $ip to find out location from my database? 如何使用此$ ip从我的数据库中查找位置?

IP addresses can be converted to numbers. IP地址可以转换为数字。 You can use this to find out which range the ip is in. 您可以使用它来找出ip所在的范围。

Using MySQL and INET_ATON : 使用MySQL和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 : 使用PHP和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. 请注意,这两种解决方案都适用于IPv4。

It would be better if you store the IP addresses in an integer representation. 如果以整数表示形式存储IP地址会更好。 You can use the MySql function INET_ATON for that. 您可以使用MySql函数INET_ATON

In PHP you can calculate it with: 在PHP中,您可以使用以下方法计算:

$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: 查询(如果您已将其存储为DB中的整数)将是:

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? 您也可以像Jim回答的那样直接在DB中进行转换,但是如果您可以预先计算数据库,那么为什么让DB进行计算呢?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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