java Jsp页面获取客户端IP地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12958759/
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
Getting IP address of client in Jsp page
提问by xrcwrn
I want to fetch Ip address of client in my jsp page and want to store on my Database.
我想在我的 jsp 页面中获取客户端的 Ip 地址并想存储在我的数据库中。
I am using following code in Jsp page to fech Ip address, but it is showing the servers Ip address.
我在 Jsp 页面中使用以下代码来获取 Ip 地址,但它显示的是服务器 Ip 地址。
<input type="hidden" name="ipaddress" value="<%=request.getRemoteAddr()%>"/>
回答by Satheesh Cheveri
In usual case the method ServletRequest.getRemoteAddr()
(or getRemoteHost()
and getRemotePort()
) should returns details of the actual client.
But, if its routed through a proxy, or a differnt servlet engine you would be getting ip of those machines. To tackle these situation you could try below operations
通常情况下,方法ServletRequest.getRemoteAddr()
(或getRemoteHost()
和getRemotePort()
)应该返回实际客户端的详细信息。但是,如果它通过代理或不同的 servlet 引擎路由,您将获得这些机器的 ip。要解决这些情况,您可以尝试以下操作
request.getHeader("VIA") --> Gateway
request.getHeader("X-FORWARDED-FOR")--> IPaddress
But this could return null if the request is directly from the client. You may handle the situation with some additional conditions to get valid data.
但是如果请求直接来自客户端,这可能会返回 null。您可以使用一些附加条件来处理这种情况以获得有效数据。
回答by betomontejo
Trying to get the client IP address from the server side with the request
object is never a reliable method.
尝试使用request
对象从服务器端获取客户端 IP 地址从来都不是可靠的方法。
The most reliable ones tend to get executed on the client side, with ActiveX, Applets, or Javascript just to name a few. However, this also poses some challenges. Check the answers to this questionjust so you know what you're up against (This is my prefered answer from that)
最可靠的往往在客户端执行,例如 ActiveX、Applet 或 Javascript。然而,这也带来了一些挑战。检查这个问题的答案,这样你就知道你在反对什么(这是我的首选答案)