Please wait...

小波Note

四川 · 成都市11 ℃
English

Java Ip Util

成都 (cheng du)8/29/2024, 1:32:53 PM1.35kEstimated reading time 4 minFavoriteCtrl + D / ⌘ + D
cover
IT FB(up 主)
Back-end development engineer
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;
  }
}