apache HttpServletRequest.getRemoteAddr() 返回错误地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1767080/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HttpServletRequest.getRemoteAddr() returning wrong address
提问by Greg Charles
We need to log the client's IP address from a Seam action. Currently, we're using the code:
我们需要从 Seam 操作中记录客户端的 IP 地址。目前,我们正在使用代码:
ExternalContext context = FacesContext.getCurrentInstance().getExternalContext();
HttpServletRequest request = (HttpServletRequest)context.getRequest();
this.remoteAddress = request.getRemoteAddr();
However, this seems to be always returning an internal address of our network, rather than the client's IP address. From my research, it seems that having a reverse proxy in the network can confuse things, but we might be able to fix it by reconfiguring our web servers. Has anyone else had this problem, and how did you solve it?
然而,这似乎总是返回我们网络的内部地址,而不是客户端的 IP 地址。根据我的研究,似乎在网络中使用反向代理可能会造成混淆,但我们或许可以通过重新配置我们的 Web 服务器来修复它。有没有其他人遇到过这个问题,你是如何解决的?
We're using JBoss 5.1 app servers and Apache web servers. Thanks!
我们使用 JBoss 5.1 应用服务器和 Apache Web 服务器。谢谢!
采纳答案by martin clayton
You can 'see through' a proxy and get the address of the original requestor from the X-FORWARDED-FORheader using
您可以“看穿”代理并X-FORWARDED-FOR使用以下方法从标头中获取原始请求者的地址
request.getHeader( "X-FORWARDED-FOR" );
I guess a misbehaving proxy between the original requestor and your server could result in the true value being lost.
我猜原始请求者和您的服务器之间行为不端的代理可能会导致真正的价值丢失。
回答by brianegge
What you need is for your reverse proxy to pass the original IP address in a special header, like x-forwarded-for. You can then retrieve this header from your servlet. Additionally, you may want to modify your log file to log this IP address. Example:
您需要的是让您的反向代理在特殊标头中传递原始 IP 地址,例如x-forwarded-for. 然后,您可以从您的 servlet 中检索此标头。此外,您可能希望修改日志文件以记录此 IP 地址。例子:
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="access_log." suffix=".txt"
fileDateFormat="yyyy-MM-dd"
pattern="%{x-forwarded-for}i %l - %t "%r" %s %b "%{referer}i" "%{user-agent}i""
resolveHosts="false"/>

