通过使用免费geoip库,解析ip。github完整项目代码:https://github.com/luoqifei/user-location/tree/master/geoipdemo

学习GeoLite2 Free Downloadable Databases api :https://dev.maxmind.com/geoip/geoip2/geolite2/

java实现如下:

public class IpDemo {public static void main(String[] args) throws Exception {//city db demo,获取城市String basePath = IpDemo.class.getResource("./geoipdb").getPath();System.out.println(basePath);Geo cityGeo = new Geo(basePath+"/GeoLite2-City.mmdb");Geo countryGeo = new Geo(basePath+"/GeoLite2-Country.mmdb");String ip1= "211.145.63.25";System.out.printf("ip=%s,country=%s,city=%s\n",ip1,countryGeo.getCountryIsoCode(ip1),cityGeo.getCityName(ip1));String ip2= "114.114.114.114";System.out.printf("ip=%s,country=%s,city=%s\n",ip2,countryGeo.getCountryIsoCode(ip2),cityGeo.getCityName(ip2));/**out putip=211.145.63.25,country=CN,city=Beijingip=114.114.114.114,country=CN,city=Nanjing*///显示城市中文名、英文名System.out.printf("ip=%s, city_CN=%s",ip1,cityGeo.getCityNameByLanguageKey(ip1,"zh-CN"));System.out.printf("ip=%s, city_CN=%s",ip2,cityGeo.getCityNameByLanguageKey(ip2,"zh-CN"));}
}
import com.maxmind.db.CHMCache;
import com.maxmind.geoip2.DatabaseReader;
import com.maxmind.geoip2.exception.GeoIp2Exception;
import com.maxmind.geoip2.model.CityResponse;
import com.maxmind.geoip2.model.CountryResponse;
import com.maxmind.geoip2.record.City;
import com.maxmind.geoip2.record.Country;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;import java.io.File;
import java.io.IOException;
import java.net.InetAddress;public class Geo {private static final Logger logger = LoggerFactory.getLogger(Geo.class);private DatabaseReader reader;public Geo(String dbfile) throws Exception {if (dbfile == null) {throw new Exception("geo database must not be null!");}try {File db = new File(dbfile);logger.info(">>> db file path: {}", db.getAbsolutePath());reader = new DatabaseReader.Builder(db).withCache(new CHMCache()).build();} catch (IOException e) {throw new Exception(String.format("geo database [%s] may not exist!", dbfile));}}public String getCityName(String ip){if(ip != null){try {InetAddress ipAddress = InetAddress.getByName(ip);String databaseType = reader.getMetadata().getDatabaseType();City city = null;if (databaseType.contains("City")) {city = reader.city(ipAddress).getCity();} else if (databaseType.contains("Country")) {logger.error("Used a wrong db which is countryDB to get city.");return null;}if (city != null && city.getName() != null) {return city.getName();}} catch (IOException | GeoIp2Exception e) {logger.warn("Geo ip parsing failed. Reason: {}", e.getMessage());}}return "unKnown city";}/*** key = {de ru pt-BR,ja, en, fr, zh-CN, es}* @param ip* @return*/public String getCityNameByLanguageKey(String ip,String language){if(ip != null){try {InetAddress ipAddress = InetAddress.getByName(ip);String databaseType = reader.getMetadata().getDatabaseType();City city = null;if (databaseType.contains("City")) {city = reader.city(ipAddress).getCity();} else if (databaseType.contains("Country")) {logger.error("Used a wrong db which is countryDB to get city.");return null;}if (city != null && city.getName() != null) {return city.getNames().get(language);}} catch (IOException | GeoIp2Exception e) {logger.warn("Geo ip parsing failed. Reason: {}", e.getMessage());}}return "unKnown city";}public String getCountryIsoCode(String ip) {return getCountryIsoCode(ip, null);}public boolean isFromChina(String ip){String code = getCountryIsoCode(ip);if(code != null){if(code.equals("CN")) {logger.info("check ip={}, result is CN",ip);return true;} else {logger.info("check ip={},result is not CN,but {}",ip,code);return false;}}else {//null set it as chinalogger.info("check ip={} , but the code is null,we set it as CN.",ip);return true;}}public String getCountryIsoCode(String ip, String defaultValue) {if (ip == null) {return defaultValue;}try {InetAddress ipAddress = InetAddress.getByName(ip);String databaseType = reader.getMetadata().getDatabaseType();Country country = null;if (databaseType.contains("City")) {CityResponse response = reader.city(ipAddress);country = response.getCountry();} else if (databaseType.contains("Country")) {CountryResponse response = reader.country(ipAddress);country = response.getCountry();}if (country != null && country.getIsoCode() != null) {return country.getIsoCode().toUpperCase();} else {return defaultValue;}} catch (IOException | GeoIp2Exception e) {logger.warn("Geo ip parsing failed. Reason: {}", e.getMessage());}return defaultValue;}}

ip地址解析成国家、城市、iso code或者按语言获取城市名相关推荐

  1. python - python 获取ip信息(国家、城市等)

    Python代码: import geoip2.databasedef from_ip_get_info(sip):reader = geoip2.database.Reader('/opt/work ...

  2. Python通过GeoIP获取IP信息(国家、城市、经纬度等)

    IP地址信息是非常重要的情报信息,通过IP可以定位到该IP所在的国家.城市.经纬度等. 获取IP信息的方式有很多,很多服务商都提供了相应的地址库或API接口服务. 如国内的ipip.net,国外的ip ...

  3. openresty开发系列40--nginx+lua实现获取客户端ip所在的国家信息

    openresty开发系列40--nginx+lua实现获取客户端ip所在的国家信息 为了实现业务系统针对不同地区IP访问,展示包含不同地区信息的业务交互界面.很多情况下系统需要根据用户访问的IP信息 ...

  4. 芯原图像信号处理器IP获得汽车功能安全标准ISO 26262认证

    通过该认证将加速芯原在电动汽车和自动驾驶等汽车领域的战略布局 2021年11月24日,中国上海--领先的芯片设计平台即服务(Silicon Platform as a Service,SiPaaS®) ...

  5. 每台计算机的ip地址解析,IP地址详解

    简单的局域网构造 什么是局域网:局域网(Local Area Network,LAN)是指在某一区域内由多台计算机互联成的计算机组.一般称为内网. 局域网通信规则:在同一个局域网中,所以的ip地址必须 ...

  6. 作者:房毓菲(1990-),女,就职于国家信息中心信息化研究部,中国智慧城市发展研究中心政策研究组副组长。...

    房毓菲(1990-),女,就职于国家信息中心信息化研究部,中国智慧城市发展研究中心政策研究组副组长,国家促进大数据发展部际联席会议办公室秘书处研究组组长,主要研究方向为智慧城市总体规划与顶层设计.信息 ...

  7. 使用Arcmap将WGS84坐标转换成国家大地坐标系2000

    1. 创建自定义地理(坐标)变换 ArcMap中打开ArcToolBox->数据管理工具->投影和变换->创建自定义地理(坐标)变换 打开对话框,选择"输出地理坐标系&qu ...

  8. WGS84坐标转换成国家大地坐标系2000

    1. 创建自定义地理(坐标)变换 ArcMap中打开ArcToolBox->数据管理工具->投影和变换->创建自定义地理(坐标)变换 打开对话框,选择"输出地理坐标系&qu ...

  9. 如何将ip修改成域名

    昨天有同学问我如何将ip修改成域名,这样的话可以使程序变得更加健壮,别人不能直接看见你的ip地址. 后来总结下分享给大家.首先找到hosts文件的位置,这个文件是系统dns默认查找的文件. windo ...

最新文章

  1. 这几个 Python 的小技巧,你会么?
  2. 【SICP练习】104 练习3.1-3.4
  3. “我只需一个周末就可以构建出这个应用!”
  4. linux wchar t char,linux 下 Linux 下char转换为wchar_t
  5. 外汇呼叫中心如何在严格监管中存续
  6. 3.2.3节:特权级
  7. cors漏洞 复现_Jsonp跨域漏洞浅析
  8. 【leetcode-83】剑指 Offer 18-2 删除排序链表中的重复元素
  9. 修改mysql的用户密码
  10. 信号量使用例子_用信号量锁定:一个例子
  11. SharePoint 2013 本地开发解决方案以及程调试
  12. 消息断点 RUN跟踪
  13. ROS机器人操作系统资料与资讯(2018年6月)
  14. IGBTMOS管的工作原理及检测方法
  15. python-华为路由器交换机批量处理ip与mac绑定
  16. MySQL课程设计2022 · 员工考勤管理系统
  17. ecshop 邮件模板 html,ecshop邮件模板默认数据与恢复.doc
  18. 攻防世界shanghai
  19. 博客SQL-Server更新数据库UPDATE语法读书笔记[图]
  20. 检查两台主机是否同处于一个局域网

热门文章

  1. 利用菜单配置文件生成菜单
  2. Oracle11gR2(二)-图形安装
  3. 开放式办公环境真是个糟糕的做法
  4. Mac OS X:刷新用户MCX记录(for SL)
  5. 宿州可以学中专计算机的学校有哪些,宿州中专学校排名榜,有哪些专业
  6. ERP实施-保密配方管理方案
  7. 计算机算法类毕业答辩问题,深度学习毕业设计答辩问题
  8. adb 命令与手机控制(提供python测试)
  9. 热电阻温度信号隔离变送分配器
  10. 京东妙手如何修改卖点图,批量修改素材教程