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


问题内容

我已经下载了ip-to-country.csv,它具有映射到国家的ip范围。如何将这些数据存储到数据库中,如何查询IP地址的范围以了解IP地址从何而来?


问题答案:

我编写了一个名为ip2c的小程序库来完成此操作。它使用webhosting.info中的数据库,但也支持Software77中的数据库。

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

Java API的用法与此类似:

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());      
}