依赖
<dependency>
<groupId>com.maxmind.geoip2</groupId>
<artifactId>geoip2</artifactId>
<version>2.8.1</version>
</dependency>
代码1
package com.util;
import com.maxmind.geoip2.DatabaseReader;
import java.io.File;
import java.net.InetAddress;
public class GeoLiteUtil {
public static String getCountry(DatabaseReader reader, String ip) throws Exception {
return reader.city(InetAddress.getByName(ip)).getCountry().getNames().get("zh-CN");
}
public static String getProvince(DatabaseReader reader, String ip) throws Exception {
return reader.city(InetAddress.getByName(ip)).getMostSpecificSubdivision().getNames().get("zh-CN");
}
public static String getCity(DatabaseReader reader, String ip) throws Exception {
return reader.city(InetAddress.getByName(ip)).getCity().getNames().get("zh-CN");
}
public static Double getLongitude(DatabaseReader reader, String ip) throws Exception {
return reader.city(InetAddress.getByName(ip)).getLocation().getLongitude();
}
public static Double getLatitude(DatabaseReader reader, String ip) throws Exception {
return reader.city(InetAddress.getByName(ip)).getLocation().getLatitude();
}
public static void main(String[] args) throws Exception {
String path = "D:\\tools\\GeoLite2-City.mmdb";
File database = new File(path);
DatabaseReader reader = new DatabaseReader.Builder(database).build();
String ip = "112.93.84.19";
String site = "国家:"+GeoLiteUtil.getCountry(reader, ip) + "\n省份:" + GeoLiteUtil.getProvince(reader, ip) + "\n城市:" + GeoLiteUtil.getCity(reader, ip)+ "\n经度:" + GeoLiteUtil.getLongitude(reader, ip)+ "\n维度:" + GeoLiteUtil.getLatitude(reader, ip);
System.out.println(site);
}
}
代码2
package com.geoLite2;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.record.*;
import java.io.File;
import java.net.InetAddress;
public class GeoTest {
public static void main(String[] args) throws Exception {
String destFilePath = new File("D:\\tools\\GeoLite2-City.mmdb").getAbsolutePath();
File database = new File(destFilePath);
DatabaseReader reader = new DatabaseReader.Builder(database).build();
InetAddress ipAddress = InetAddress.getByName("112.93.84.19");
CityResponse response = reader.city(ipAddress);
Country country = response.getCountry();
System.out.println(country.getIsoCode());
System.out.println(country.getName());
System.out.println(country.getNames().get("zh-CN"));
Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println(subdivision.getName());
System.out.println(subdivision.getIsoCode());
System.out.println(subdivision.getNames().get("zh-CN"));
City city = response.getCity();
System.out.println(city.getName());
Postal postal = response.getPostal();
System.out.println(postal.getCode());
System.out.println(city.getNames().get("zh-CN"));
Location location = response.getLocation();
System.out.println(location.getLatitude());
System.out.println(location.getLongitude());
}
}