- 引入库
在build.gradle中引用库
compile 'com.maxmind.geoip2:geoip2:2.8.0'
import com.maxmind.geoip2.*;
import com.maxmind.geoip2.model.*;
import java.io.*;
import java.net.*;
public class GeoLocationIp {
public static void main(String[] args) throws Exception {
File database = new File("/Users/edward/Documents/GeoLite2-City_20221025/GeoLite2-City.mmdb");
DatabaseReader dbReader = new DatabaseReader.Builder(database).build();
CityResponse response = dbReader.city(InetAddress.getByName("110.242.68.66"));
System.out.println(response);
}
}
输出中可以看到是石家庄的(这是百度的一个ip):
com.maxmind.geoip2.model.CityResponse
[{
"city": {
"names": {
"en": "Shijiazhuang"
}
},
"continent": {
"code": "AS",
"geoname_id": 6255147,
"names": {
"zh-CN": "亚洲",
"es": "Asia"
}
},
"country": {
"geoname_id": 1814991,
"iso_code": "CN",
"names": {
"zh-CN": "中国",
"es": "China"
}
},
"location": {
"latitude": 38.0428,
"longitude": 114.515
},
"maxmind": {},
"postal": {},
"registered_country": {},
"represented_country": {},
"subdivisions": [{
"names": {
"en": "Hebei"
}
}],
"traits": {
"ip_address": "110.242.68.66",
"is_anonymous_proxy": false,
"is_legitimate_proxy": false,
"is_satellite_provider": false
}
}]
- (可选) 在使用过程中, 我发现上面的maxmind的数据并不是很准确, 毕竟是免费版本, 所以我又找了个url, 这个的识别精度更高, 而且是免费的无需注册就可以下载.
csdn: 下载地址
官网下载地址
参考
- geoip 收费版在线测试地址