java 获取客户端真实IP工具类

随着nginx等工具兴起,单纯采用 HttpServletRequest.getRemoteHost()已经不能获取客户端的真实IP。以下是一个Java获取客户端真实IP工具类。

import javax.servlet.http.HttpServletRequest;

public class RequestUtil {

    public static String getRealIp(HttpServletRequest request) {
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }

        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }
}

你可能感兴趣的:(Java,java,工具类)