简体   繁体   中英

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 :

ServletRequest还提供方法java.lang.String getRemoteAddr() ()有关更多详细信息,请参见https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getRemoteAddr()

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();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM