java如何获取IP和IP的归属地?

在Java中,获取IP地址通常指的是获取本地机器的IP地址或者通过某种方式(如HTTP请求)获取的远程IP地址。代码案例如下:

而要获取IP的归属地(地理位置信息),则通常需要使用第三方IP地址查询服务,我这里使用的是 ip2region开源IP库。代码操作步骤如下:

1.导入ip2region库:

2.在pom文件中包含该目录下的对应资源

3.根据IP获取归属地

java 复制代码
public static String getAddressLog(String userPhone, String ip) {
    try {
        HttpServletRequest request = RequestUtil.getRequest();
        log.info("======> 获取客户端IP地址:clientIP:{}", ip);
        if (StrUtil.isBlank(ip)) {
         log.error("获取用户ip失败,用户手机号 = " + userPhone);
        } else {
          IpLocation ipLocation = IPUtil.getLocation(ip);
          if (ObjectUtil.isNotNull(ipLocation.getProvince())) {
              //根据业务需求来确定需要定位到省还是省-市,我这里就直接是定位到省
              String address = ipLocation.getProvince();
              log.info("======> IP解析后的地址信息:{}", address);
              //注意:如果是内网IP的话,这里将查询不到归属地,而会返回内网,
              //这里如果是内网IP就直接处理变成广东省。
              if (StringUtils.isNotEmpty(address)){
                 return address.contains("内网") ? "广东省" : address;
              }
           }
         }
     } catch (Exception e) {
       log.error("通过ip获取用户位置失败,用户phone = {}", userPhone);
       log.error("通过ip获取用户位置失败,e = {}", e);
     }
}

 /**
     * 根据iP获取归属地信息
     */
public static IpLocation getLocation(String ip) {
   IpLocation location = new IpLocation();
   location.setIp(ip);
   try (InputStream inputStream = IPUtil.class.getResourceAsStream("/ipdb/ip2region.xdb");) {
     byte[] bytes = IoUtil.readBytes(inputStream);
     Searcher searcher = Searcher.newWithBuffer(bytes);
     String region = searcher.search(ip);
     log.info("============> region:{}", region);
     if (StrUtil.isNotBlank(region)) {
       // xdb返回格式 国家|区域|省份|城市|ISP,
       // 只有中国的数据绝大部分精确到了城市,其他国家部分数据只能定位到国家,后前的选项全部是0
       String[] result = region.split("\\|");
       location.setCountry(ZERO.equals(result[0]) ? StrUtil.EMPTY : result[0]);
       location.setProvince(ZERO.equals(result[2]) ? StrUtil.EMPTY : result[2]);
       location.setCity(ZERO.equals(result[3]) ? StrUtil.EMPTY : result[3]);
       location.setIsp(ZERO.equals(result[4]) ? StrUtil.EMPTY : result[4]);
      }
            searcher.close();
   } catch (Exception e) {
      e.printStackTrace();
      return location;
   }
   return location;
}

4.结果展示

相关推荐
extrao2 天前
🚀 Kea DHCP4 自动分配系统完整搭建
网络协议
不做菜鸟的网工4 天前
BGP特性
网络协议
MrSYJ4 天前
TCP协议理解
后端·tcp/ip
明月_清风6 天前
开发者网络概念全扫盲:一篇搞定
后端·网络协议
刘马想放假6 天前
Modbus 全栈技术解析:TCP、RTU、ASCII、RTU over TCP
数据结构·网络协议
王二端茶倒水7 天前
一套可落地的无线运营方案,不能只管 AP,还要管用户、计费和运维
网络协议
162723816087 天前
EtherCAT 分布式时钟(DC)原理与配置实战:把多轴真正"对齐到同一时刻"
网络协议
王二端茶倒水8 天前
宽带无线项目,怎么从一次性交付变成长期运营收入?
网络协议
用户2530171996279 天前
第6篇:从技术到产品 — Ghost Proxifier 的设计哲学
网络协议