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

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

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

1.导入ip2region库:

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

3.根据IP获取归属地

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.结果展示

  • 3
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Java 中,我们可以使用第三方库来获取 IP归属地信息。其中一个常用的库是 GeoIP2,它基于 MaxMind 的 GeoIP2 数据库。 首先,需要将 GeoIP2 库添加到项目中。可以在 Maven 或 Gradle 构建脚本中添加相应的依赖项。 然后,我们可以使用 GeoIP2 提供的 API 来查询 IP归属地。以下是一个示例代码: ```java import com.maxmind.geoip2.DatabaseReader; import com.maxmind.geoip2.model.CityResponse; import com.maxmind.geoip2.record.Country; import java.io.File; import java.io.IOException; import java.net.InetAddress; public class IPUtils { public static String getIPCountry(String ip) { try { File database = new File("GeoIP2-City.mmdb"); DatabaseReader reader = new DatabaseReader.Builder(database).build(); InetAddress ipAddress = InetAddress.getByName(ip); CityResponse response = reader.city(ipAddress); Country country = response.getCountry(); return country.getName(); } catch (IOException e) { e.printStackTrace(); return null; } } public static void main(String[] args) { String ip = "123.456.789.0"; String country = getIPCountry(ip); System.out.println("IP " + ip + " 的归属地是:" + country); } } ``` 在上述示例中,我们通过 `getIPCountry` 方法传入一个 IP 地址,并在 `main` 方法中调用该方法来获取IP归属地信息。具体的归属地信息包括国家、地区、城市等,可以根据需要进行扩展和处理。 需要注意的是,在运行代码之前,我们需要下载并导入 GeoIP2 数据库文件 `GeoIP2-City.mmdb`,该文件包含了 IP 地址和归属地信息的映射关系。可以从 MaxMind 的官网或其他数据源获取该文件。 这样,我们就可以通过 Java获取 IP归属地信息了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值