AddressUtils.java 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package com.ruoyi.common.utils.ip;
  2. import cn.hutool.core.net.NetUtil;
  3. import cn.hutool.http.HtmlUtil;
  4. import cn.hutool.http.HttpUtil;
  5. import com.ruoyi.common.config.RuoYiConfig;
  6. import com.ruoyi.common.constant.Constants;
  7. import com.ruoyi.common.utils.JsonUtils;
  8. import com.ruoyi.common.utils.StringUtils;
  9. import lombok.extern.slf4j.Slf4j;
  10. import java.util.Map;
  11. /**
  12. * 获取地址类
  13. *
  14. * @author Lion Li
  15. */
  16. @Slf4j
  17. public class AddressUtils {
  18. // IP地址查询
  19. public static final String IP_URL = "http://whois.pconline.com.cn/ipJson.jsp";
  20. // 未知地址
  21. public static final String UNKNOWN = "XX XX";
  22. public static String getRealAddressByIP(String ip) {
  23. String address = UNKNOWN;
  24. if (StringUtils.isBlank(ip)) {
  25. return address;
  26. }
  27. // 内网不查询
  28. ip = "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : HtmlUtil.cleanHtmlTag(ip);
  29. if (NetUtil.isInnerIP(ip)) {
  30. return "内网IP";
  31. }
  32. if (RuoYiConfig.isAddressEnabled()) {
  33. try {
  34. String rspStr = HttpUtil.createGet(IP_URL)
  35. .body("ip=" + ip + "&json=true", Constants.GBK)
  36. .execute()
  37. .body();
  38. if (StringUtils.isEmpty(rspStr)) {
  39. log.error("获取地理位置异常 {}", ip);
  40. return UNKNOWN;
  41. }
  42. Map<String, String> obj = JsonUtils.parseMap(rspStr);
  43. String region = obj.get("pro");
  44. String city = obj.get("city");
  45. return String.format("%s %s", region, city);
  46. } catch (Exception e) {
  47. log.error("获取地理位置异常 {}", ip);
  48. }
  49. }
  50. return address;
  51. }
  52. }