AddressUtils.java 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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 ruoyi
  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. // 内网不查询
  25. ip = "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : HtmlUtil.cleanHtmlTag(ip);
  26. if (NetUtil.isInnerIP(ip)) {
  27. return "内网IP";
  28. }
  29. if (RuoYiConfig.isAddressEnabled()) {
  30. try {
  31. String rspStr = HttpUtil.createGet(IP_URL)
  32. .body("ip=" + ip + "&json=true", Constants.GBK)
  33. .execute()
  34. .body();
  35. if (StringUtils.isEmpty(rspStr)) {
  36. log.error("获取地理位置异常 {}", ip);
  37. return UNKNOWN;
  38. }
  39. Map<String, String> obj = JsonUtils.parseMap(rspStr);
  40. String region = obj.get("pro");
  41. String city = obj.get("city");
  42. return String.format("%s %s", region, city);
  43. } catch (Exception e) {
  44. log.error("获取地理位置异常 {}", ip);
  45. }
  46. }
  47. return address;
  48. }
  49. }