java 獲取客戶端真實ip

hcmony發表於2017-10-20
package com.hcmony.utils;

import javax.servlet.http.HttpServletRequest;

import com.alibaba.dubbo.common.utils.StringUtils;

/**
 * 獲取客戶端IP
 * @Creator hcmony
 * @Created 2017-10-17 15:52:00
 * @Modifier hcmony
 * @Updated 2017-10-17 15:52:00
 * @Description
 * @Version BUILD1001
 */
public class GetIpAddressUtils {
   public static String getRemoteIp(HttpServletRequest request) {
      if (request == null) {
         return null;
      }
      // try-get
      String ip = request.getHeader("X-Forwarded-For");
      if (StringUtils.isBlank(ip) == false && ("unknown".equalsIgnoreCase(ip) == false)) {
         final int i = ip.indexOf(',');
         return (i == -1) ? ip : ip.substring(0, i);
      }
      if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
         ip = request.getHeader("X-Real-IP");
      }
      if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
         ip = request.getHeader("Proxy-Client-IP");
      }
      if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
         ip = request.getHeader("WL-Proxy-Client-IP");
      }
      if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
         ip = request.getRemoteAddr();
      }
      return ip;
   }
   
    @SuppressWarnings("unused")
   public static String getHeader(HttpServletRequest request, String headName) {
           String value = request.getHeader(headName);
           return !StringUtils.isBlank(value) && !"unknown".equalsIgnoreCase(value) ? value : "";
       }

}

相關文章