在Java中,获取IP地址通常指的是获取本地机器的IP地址或者通过某种方式(如HTTP请求)获取的远程IP地址。代码案例如下:
而要获取IP的归属地(地理位置信息),则通常需要使用第三方IP地址查询服务,我这里使用的是 ip2region开源IP库。代码操作步骤如下:
1.导入ip2region库:
2.在pom文件中包含该目录下的对应资源
3.根据IP获取归属地
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
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.结果展示