带有数据库的国家/地区的 IP 地址

2022-01-14 00:00:00 geolocation ip-geolocation java

我已下载 ip-to-country.csv,其中包含映射到国家/地区的 IP 范围.我应该如何将这些数据存储到数据库中,如何查询 IP 地址在什么范围内才能知道 IP 地址来自哪里?

I have downloaded ip-to-country.csv that has ip ranges that are mapped to countries. How should I store this data to database and how can I query in what range Ip address is to know where Ip address is coming from?

推荐答案

我写了一个小库,叫做 ip2c 做到这一点.它使用来自 webhosting.info 的数据库,但也支持来自 Software77.

I wrote a small lib called ip2c to do just that. it uses the database from webhosting.info but also supports that from Software77.

它将 CSV 信息转换为紧凑的二进制格式,并且可以直接在文件、内存或内存映射文件中进行搜索.

It converts the CSV info a compact binary format and can do the search straight on the file, in memory or in a memory mapped file.

Java API 用法类似:

The Java API usage is similar to this:

String ip = 85.64.225.159;
int caching1 = IP2Country.NO_CACHE;  // Straight on file, Fastest startup, slowest queries
int caching2 = IP2Country.MEMORY_MAPPED; // Memory mapped file, fast startup, fast queries.
int caching3 = IP2Country.MEMORY_CACHE; // load file into memory, slowerst startup, fastest queries
IP2Country ip2c = new IP2Country(caching1);
Country c = ip2c.getCountry(ip);
if (c == null)
{
        System.out.println("UNKNOWN");                          
}
else
{
        // will output IL ISR ISRAEL
        System.out.println(c.get2cStr() + " " + c.get3cStr() + " " + c.getName());      
}

相关文章