お待ちください...

小波Note

四川 · 成都市14 ℃
日本語

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;
  }
}