maxmind免费数据库maven位置:用来获取所要用的数据库文件(GeoLite2-City.mmdb)
<dependency>
<groupId>org.elasticsearch</groupId>
<artifactId>geolite2-databases</artifactId>
<version>20151029</version>
</dependency>
2. 示例
import java.io.File;
import java.net.InetAddress;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
/**
* @author aben
*/
public class IPMain {
private static String version2 = "E:\\GeoLite2-City.mmdb";
public static void main(String[] args) {
IPMain main = new IPMain();
System.out.println(main.getCity("119.123.163.222", new File(version2)));
}
public String getCity(String ipStr, File dataBaseFile) {
String result = "";
try {
DatabaseReader reader = new DatabaseReader.Builder(dataBaseFile).build();
InetAddress ip = InetAddress.getByName(ipStr);
CityResponse response = reader.city(ip);
// 获取所在洲
String zhouStr = response.getContinent().getNames().get("zh-CN");
// 获取所在国家
String guoStr = response.getCountry().getNames().get("ja");
// 获取所在省份
String shengStr = response.getSubdivisions().get(0).getNames().get("zh-CN");
// 获取所在城市(由于是免费版的数据库,查找城市的时候是不准确的)
String shiStr = response.getCity().getNames().get("zh-CN");
result = zhouStr + guoStr + shengStr + shiStr;
} catch (Exception e) {
;
}
return result;
}
}
注 : 以上用到的包的maven位置:
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.6.0</version>
</dependency>