1.引入mavenjar包
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>com.maxmind.db</groupId>
<artifactId>maxmind-db</artifactId>
<version>1.0.0</version>
</dependency>
2.下载数据库文件、解压
https://geolite.maxmind.com/download/geoip/database/GeoLite2-City.tar.gz
3.写java代码
package com.example.demo;
import java.io.File;
import java.net.InetAddress;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.City;
import com.maxmind.geoip2.record.Country;
import com.maxmind.geoip2.record.Location;
import com.maxmind.geoip2.record.Subdivision;
public class GenIpUtils {
public static void main(String[] args) throws Exception {
String ip = "199.201.64.4";
GenIpUtils.getCityByIP(ip);
}
public static void getCityByIP(String ip) throws Exception{
// 创建 GeoLite2 数据库
File database = new File("F:\\GeoLite2-City.mmdb");
// 读取数据库内容
DatabaseReader reader = new DatabaseReader.Builder(database).build();
InetAddress ipAddress = InetAddress.getByName(ip);
// 获取查询结果
CityResponse response = reader.city(ipAddress);
// 获取国家信息
Country country = response.getCountry();
System.out.println("国家code:"+country.getIsoCode());
System.out.println("国家:"+country.getNames().get("zh-CN"));
// 获取省份
Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println("省份code:"+subdivision.getIsoCode());
System.out.println("省份:"+subdivision.getNames().get("zh-CN"));
//城市
City city = response.getCity();
System.out.println("城市code:"+city.getGeoNameId());
System.out.println("城市:"+city.getName());
// 获取城市
Location location = response.getLocation();
System.out.println("经度:"+location.getLatitude());
System.out.println("维度:"+location.getLongitude());
}
}