java 在 GWT 和 Google App Engine 中获取客户端 IP 地址
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1836461/
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
Obtaining clients IP address in GWT and Google App Engine
提问by Bostone
I have a need to capture IP address of the client in my GWT/GAE (Java) application. Since GAE does not support full set of java.net APIs I cannot do code such as snippet below. Can anyone suggest reliable way of achieving the same?
我需要在我的 GWT/GAE (Java) 应用程序中捕获客户端的 IP 地址。由于 GAE 不支持全套 java.net API,因此我无法执行如下代码段之类的代码。任何人都可以建议实现相同目标的可靠方法吗?
for (final Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {
final NetworkInterface intf = en.nextElement();
for (final Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {
final InetAddress ip = enumIpAddr.nextElement();
if (!ip.isLoopbackAddress() && !ip.isLinkLocalAddress() && !ip.isAnyLocalAddress()) {
return ip.getHostAddress().toString();
}
}
}
For Python version one can do:
对于 Python 版本,可以执行以下操作:
os.environ['REMOTE_ADDR']
or
或者
String ip = self.request.remote_addr;
But what would be a Java equivalent?
但是什么是 Java 等价物?
回答by Bostone
OK - got it. In your Servlet which should extend RemoteServiceServletdo this:
好的,我知道了。在你应该扩展的 Servlet 中RemoteServiceServlet:
final String ip = getThreadLocalRequest().getRemoteAddr();
回答by amanas
If you are behind a proxy, for example, if you use ProxyPass and ProxyPassReverse you could find useful this:
如果您在代理后面,例如,如果您使用 ProxyPass 和 ProxyPassReverse,您会发现以下内容很有用:
this.getThreadLocalRequest().getHeader("X-FORWARDED-FOR")
回答by mlkammer
Actually, if you want the IP address you might want to use getRemoteAddr instead of getRemoteHost.
实际上,如果您想要 IP 地址,您可能需要使用 getRemoteAddr 而不是 getRemoteHost。
String ip = getThreadLocalRequest().getRemoteAddr();
String host = getThreadLocalRequest().getRemoteHost();
- getRemoteAddrgives you the internet protocol (IP) address of the client.
- getRemoteHostgives you the fully qualified name of the client, the IP if the host name is empty.
- getRemoteAddr为您提供客户端的 Internet 协议 (IP) 地址。
- getRemoteHost为您提供客户端的完全限定名称,如果主机名为空,则为 IP。
See the Oracle Javadoc: http://docs.oracle.com/javaee/7/api/javax/servlet/ServletRequest.html#getRemoteAddr%28%29
请参阅 Oracle Javadoc:http: //docs.oracle.com/javaee/7/api/javax/servlet/ServletRequest.html#getRemoteAddr%28%29

