package cn.com.qmth.stmms.common.utils;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

public class RequestIPUtil implements ApiConstant {

    private static final String FIELD_IP = "_IP_";

    public static String getIpAddress(HttpServletRequest request) {
        Object obj = request.getAttribute(FIELD_IP);
        if (obj instanceof String) {
            return (String) obj;
        } else {
            String ip = request.getHeader("X-FORWARDED-FOR");
            if (StringUtils.isEmpty(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("X-Real-IP");
            }
            if (StringUtils.isEmpty(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("WL-Proxy-Client-IP");
            }
            if (StringUtils.isEmpty(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getHeader("HTTPCLIENTIP");
            }
            if (StringUtils.isEmpty(ip) || IP_UNKNOWN.equalsIgnoreCase(ip)) {
                ip = request.getRemoteAddr();
            }
            if (StringUtils.isEmpty(ip)) {
                ip = IP_UNKNOWN;
            } else if (ip.contains(",")) {
                ip = ip.split(",")[0];
            }
            request.setAttribute(FIELD_IP, ip);
            return ip;
        }
    }

}
