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 :
            Asked
            
        
        
            Active
            
        
            Viewed 3,386 times
        
    2 Answers
1
            
            
        The ServletRequest also provides the method java.lang.String getRemoteAddr() see https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getRemoteAddr() for more details.
 
    
    
        DrHopfen
        
- 752
- 3
- 13
1
            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();
}
 
    
    
        Ahmad Shahwan
        
- 1,662
- 18
- 29
