【问题标题】:How can I select in MySQL only the users from a certain country, based on their IP?如何在 MySQL 中根据 IP 仅选择来自某个国家/地区的用户?
【发布时间】:2023-03-29 10:25:01
【问题描述】:

我正在通过查询 mysql 来分析来自不同国家的用户,但我目前只对分别分析来自加拿大的用户和来自其他国家的用户感兴趣。我有他们的 IP(他们是手机游戏玩家,他们玩我们的游戏),但我不知道如何根据国家/地区过滤它们...您能帮忙吗?

【问题讨论】:

  • 只是在这里猜测,但你可以抓取这个:lite.ip2location.com/canada-ip-address-ranges 然后将范围放在一个表格中,然后将你拥有的数据与这些数据进行比较。
  • 看起来需要几年时间才能做到这一点......
  • 有些 API 会返回 IP 的位置。这不是万无一失的,但它相当准确。按 IP 搜索地理位置
  • 这是加拿大nirsoft.net/countryip/ca.html的IP范围,希望对您有所帮助。
  • 看看这个IP JSON。他们有一个使用 JSON 的国家/地区 API 的 IP。您可以在服务器端使用 CURL 调用它,以根据 IP 地址获取国家/地区。

标签: mysql select filter ip


【解决方案1】:

简而言之,在所有情况下,您都需要加拿大的 IP。但是即使您有数据库,也可以在特定范围内检查 IP 的解决方案或不消耗时间,

您可以使用的服务 (API) 太多;到目前为止对我来说最好的是maxmind,他们有免费和付费版本,具体取决于你想要多少细节。

选择您要使用的 API 后,在您的表中添加一个名为 country 的列,并使用 API 根据 IP 地址对其进行更新。这样您将执行一个简单的查询并按国家/地区进行过滤

在我提到的情况下,我使用 maxmind 并使用 perl 使用 Geo::IP module - you can find more details here 进行此操作。

使用 Perl 的简单示例:

use 5.014;
use DBI;
use Geo::IP;    
#sudo apt-get install libgeo-ip-perl (then) sudo cpanm Geo::IP

my $table   = 'Gamers';
my $country;

#Connect to you database
my $dbh_s   = DBI->connect(Database(), User(), Pass()) or die($DBI::errstr);

#select the id and IPs of the gamers
my $sth_m   = $dbh_s->prepare("SELECT id, request_ip FROM $table WHERE request_ip IS NOT NULL AND country = '0'"); 
$sth_m->execute();
my $rows    = $sth_m->fetchall_arrayref; die("\n") unless ($rows);

# prepare the query to update the country
my $sth_u   = $dbh_s->prepare("UPDATE $table SET country = ?, updated_time = now() WHERE id = ?");

# here you can use the specific .dat you took from the maxmind
my $gi      = Geo::IP->open("/usr/local/share/GeoIP/GeoIP.dat", GEOIP_STANDARD ) or die ("Can't init Geo\n");

# Do the magic (Take every IP and check which coutry)
foreach my $row (@{$rows}) { 

    # I am not filtering IPv6 here so I just send them to US
    if (@$row[2] =~ ':')    { $country = 'US'; } #IPv6
    # The lite free database don't all details sometimes some IPs don't exsit to I just ignore them and mark them by 'WW'
    else                    { $country = $gi->country_code_by_addr(@$row[2]) || 'WW'; }

    $sth_u->execute($country, @$row[0]);
}

# close the connection to the databse
$dbh_s->disconnect;

您可以将此脚本放在 cron 中,然后每小时或每天执行一次。然后只需 SELECT gamer FROM gamers WHERE country = 'CA';

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-02-18
    • 2020-05-20
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多