0
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

我有一个包含国家、州和城市的 ip 列表的表。

我的问题是如何从我的数据库中检测用户的 ip 位置

如果我使用 php$ip = $_SERVER["HTTP_CLIENT_IP"]; , HTTP_X_FORWARDED_FOR & REMOTE_ADDR找出用户的 ip。

如何使用此变量从我的数据库中找出哪个国家、州和城市?

ip_start 和 ip_end 如何工作?

前任。如果我的 ip 是 $ip=123.243.51.83;

如何使用此 $ip 从我的数据库中查找位置?

4

2 回答 2

1

IP 地址可以转换为数字。您可以使用它来找出 ip 在哪个范围内。

使用 MySQL 和INET_ATON

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

使用 PHP 和ip2long

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

请注意,这两种解决方案都适用于 IPv4。

于 2013-08-13T12:41:26.760 回答
1

如果您以整数表示形式存储 IP 地址会更好。您可以为此使用 MySql 函数INET_ATON

在 PHP 中,您可以使用以下方法计算它:

$address = '174.36.207.186';

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

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

查询(如果您已将其作为整数存储在 DB 中)将是:

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

您也可以像 Jim 回答的那样直接在数据库中进行覆盖,但是如果您可以预先计算,为什么还要让数据库进行计算呢?

于 2013-08-13T12:48:42.357 回答