javaservletsip-addressclientip

How can I get the IP address from a ServletRequest, not a HTTPServletRequest ?


I'm trying to find a Java method that would get a ServletRequest and finds the IP address for that request. Something like this method that I found but would receive a ServletRequest instead of HTTPServletRequest :


Solution

  • I'd check if the request is an HTTP request, if so, use the method proposed in the other question. Otherwise, I'd trust the method getRemoteAddr() blindly.

    if (request instanceof HTTPServletRequest) {
        HTTPServletRequest httpRequest = (HTTPServletRequest) request;
        // read X-Forwarded-For header, etc. etc.
    } else {
        ip = request.getRemoteAddr();
    }