Search code examples
javahttphttpwebrequesthttp-headers

How can I retrieve IP address from HTTP header in Java


I am curious if there is any library that handles already this kind of stuff, or I have to do it by myself once again. So, the thing is I want to get IP address field from the visitors HTTP header request on my server, and do the whole thing in Java? Any help would be nice. Thanks in advance.


Solution

  • Use the getHeader(String Name) method of the javax.servlet.http.HttpServletRequest object to retrieve the value of Remote_Addr variable. Here is the sample code:

    String ipAddress = request.getHeader("Remote_Addr");
    

    If this code returns empty string, then use this way:

    String ipAddress = request.getHeader("HTTP_X_FORWARDED_FOR");
    
    if (ipAddress == null) {
        ipAddress = request.getRemoteAddr();
    }