使用 GeoLite 实现IP精准定位(Java实现)


maxmind提供的免费GeoLite数据库可以使我们简单方便的对 全球ip 进行过定位。下面介绍使用方法 参考自官方, 写下来留着以后备用:

1 下载mmdb文件数据库和添加依赖

GeoLite2.mmdb官方下载地址

如果官方下载较慢的话也可以使用百度云地址

Maven依赖

<dependency> 
    <groupId>com.maxmind.geoip2</groupId> 
    <artifactId>geoip2</artifactId>
    <version>v2.3.0</version>
</dependency>

2 使用

//GeoIP2-City 数据库文件
File database = new File("/path/to/GeoIP2-City.mmdb");

// 创建 DatabaseReader对象
DatabaseReader reader = new DatabaseReader.Builder(database).build();

InetAddress ipAddress = InetAddress.getByName("128.101.101.101");

CityResponse response = reader.city(ipAddress);

Country country = response.getCountry();
System.out.println(country.getIsoCode());            // 'US'
System.out.println(country.getName());               // 'United States'
System.out.println(country.getNames().get("zh-CN")); // '美国'

Subdivision subdivision = response.getMostSpecificSubdivision();
System.out.println(subdivision.getName());    // 'Minnesota'
System.out.println(subdivision.getIsoCode()); // 'MN'

City city = response.getCity();
System.out.println(city.getName()); // 'Minneapolis'

Postal postal = response.getPostal();
System.out.println(postal.getCode()); // '55455'

Location location = response.getLocation();
System.out.println(location.getLatitude());  // 44.9733
System.out.println(location.getLongitude()); // -93.2323

参考

[1] geolite2-开源数据库
[2] GeoIP2 Java API

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 175,149评论 25 709
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,323评论 19 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 47,052评论 6 342
  • 1 toast 显示一个弱提示,可选择多少秒之后消失1.1 使用方法3.1 入参| 名称 | 类型 | 描述 ...
    Ribbon_2bc2阅读 2,649评论 0 0
  • 今日打卡,今天画了线条画,和彩铅,感觉越画越难看 先来今天画的线条画 再来一张全部的 最后来上彩铅,丑死了
    三千筱夜阅读 1,560评论 2 3