我已经下载了ip-to-country.csv,它具有映射到国家/地区的IP范围。我应该如何将这些数据存储到数据库中?如何查询IP地址在哪个范围内知道IP地址的来源?
答案 0 :(得分:5)
我写了一个名为ip2c的小型lib来做这件事。它使用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());
}
答案 1 :(得分:3)
查看IP-to-Country Handbook
ip-to-country.csv文件包含五个字段:
* Begining of IP address range
* Ending of IP address range
* Two-character country code based on ISO 3166
* Three-character country code based on ISO 3166
* Country name based on ISO 3166
您可以通过创建包含以下字段的表格将此数据导入任何数据库:
FIELD DATA TYPE FIELD DESCRIPTION
IP_FROM NUMERICAL (DOUBLE) Beginning of IP address range.
IP_TO NUMERICAL (DOUBLE) Ending of IP address range.
COUNTRY_CODE2 CHAR(2) Two-character country code based on ISO 3166.
COUNTRY_CODE3 CHAR(3) Three-character country code based on ISO 3166.
COUNTRY_NAME VARCHAR(50) Country name based on ISO 3166
您可以在将数据导入其中后查询上表,通过发出以下Select语句查找相应IP Number的国家/地区:
SELECT COUNTRY_NAME FROM <TableName> WHERE IP_FROM <= IP Number and IP_TO >= IP Number
其中给定的A.B.C.D IP的IP号由下式计算:
IP Number = A x (256*256*256) + B x (256*256) + C x 256 + D
答案 2 :(得分:2)
对于IPv4,您可以使用以下格式存储:
当您需要查找IP地址时,请执行以下查询
SELECT Country from GeoIP where IpFrom < $IP and $IP < $IpTo
这将为您提供IP地址的国家/地区
答案 3 :(得分:1)
您只能为范围的ipTo(高边界)值构建索引并使用查询:
select country from geoip where $ip <= ipTo limit 1
(假设范围不像MaxMind数据库那样重叠)