maxmind免費數據庫maven位置:用來獲取所要用的數據庫文件(GeoLite2-City.mmdb)java
<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位置:elasticsearch
<dependency> <groupId>com.maxmind.geoip2</groupId> <artifactId>geoip2</artifactId> <version>2.6.0</version> </dependency>