请稍等...

小波Note

四川 · 成都市多云16 ℃
中文

Java Ip 工具类

成都 (cheng du)2024/8/29 13:32:531.35k预计阅读时间 4 分钟收藏Ctrl + D / ⌘ + D
cover
IT FB(up 主)
后端开发工程师
java
        import jakarta.servlet.http.HttpServletRequest;

public class IpUtils {

  private static final String[] HEADERS = {
          "X-Forwarded-For",
          "Proxy-Client-IP",
          "WL-Proxy-Client-IP",
          "HTTP_X_FORWARDED_FOR",
          "HTTP_X_FORWARDED",
          "HTTP_X_CLUSTER_CLIENT_IP",
          "HTTP_CLIENT_IP",
          "HTTP_FORWARDED_FOR",
          "HTTP_FORWARDED",
          "HTTP_VIA",
          "REMOTE_ADDR",
          "X-Real-IP"
  };

  /**
   * 判断ip是否为空,空返回true
   * @param  ip
   * @return boolean
   */
  public static boolean isEmptyIp(final String ip){
    return (ip == null || ip.length() == 0 || ip.trim().equals("") || "unknown".equalsIgnoreCase(ip));
  }


  /***
   * 获取客户端ip地址(可以穿透代理)
   * @param request HttpServletRequest
   * @return string
   */
  public static String getIp(HttpServletRequest request) {
    String ip = "";
    for (String header : HEADERS) {
      ip = request.getHeader(header);
      if(!isEmptyIp(ip)) {
        break;
      }
    }
    if(isEmptyIp(ip)){
      ip = request.getRemoteAddr();
    }
    if(!isEmptyIp(ip) && ip.contains(",")){
      ip = ip.split(",")[0];
    }

    if (ip.contains(":") && ip.contains(".")) {
      ip = ip.substring(ip.lastIndexOf(":") + 1);
    }
    return ip;
  }
}