如何从ServletRequest获取IP地址,而不是HTTPServletRequest?

时间:2018-06-05 14:41:23

标签: java servlets ip-address clientip

我正在尝试找到一个可以获得ServletRequest并找到该请求的IP地址的Java方法。我找到的this方法之类的东西,但会收到ServletRequest而不是HTTPServletRequest:

2 个答案:

答案 0 :(得分:1)

ServletRequest还提供方法java.lang.String getRemoteAddr(),详见https://docs.oracle.com/javaee/6/api/javax/servlet/ServletRequest.html#getRemoteAddr()

答案 1 :(得分:1)

我检查请求是否是HTTP请求,如果是,请使用其他问题中提出的方法。否则,我会盲目地信任方法getRemoteAddr()

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