How do I get the remote address of a client in servlet?

前端 未结 10 2045
刺人心
刺人心 2020-11-22 07:32

Is there any way that I could get the original IP address of the client coming to the server? I can use request.getRemoteAddr(), but I always seem to get the IP

10条回答
  •  天涯浪人
    2020-11-22 08:07

    Why don't use a more elegant solution like this?

    private static final List IP_HEADERS = Arrays.asList("X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR");
    
    public static String getClientIpAddr(HttpServletRequest request) {
        return IP_HEADERS.stream()
            .map(request::getHeader)
            .filter(Objects::nonNull)
            .filter(ip -> !ip.isEmpty() && !ip.equalsIgnoreCase("unknown"))
            .findFirst()
            .orElseGet(request::getRemoteAddr);
    }
    

    Deduplicate your code!

提交回复
热议问题