Bostone
Bostone

Reputation: 37126

Obtaining clients IP address in GWT and Google App Engine

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?

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:

os.environ['REMOTE_ADDR'] 

or

String ip = self.request.remote_addr;

But what would be a Java equivalent?

Upvotes: 8

Views: 11736

Answers (3)

mlkammer
mlkammer

Reputation: 200

Actually, if you want the IP address you might want to use getRemoteAddr instead of getRemoteHost.

String ip   = getThreadLocalRequest().getRemoteAddr();
String host = getThreadLocalRequest().getRemoteHost();
  • getRemoteAddr gives you the internet protocol (IP) address of the client.
  • getRemoteHost gives you the fully qualified name of the client, the IP if the host name is empty.

See the Oracle Javadoc: http://docs.oracle.com/javaee/7/api/javax/servlet/ServletRequest.html#getRemoteAddr%28%29

Upvotes: 0

amanas
amanas

Reputation: 520

If you are behind a proxy, for example, if you use ProxyPass and ProxyPassReverse you could find useful this:

this.getThreadLocalRequest().getHeader("X-FORWARDED-FOR") 

Upvotes: 6

Bostone
Bostone

Reputation: 37126

OK - got it. In your Servlet which should extend RemoteServiceServlet do this:

final String ip = getThreadLocalRequest().getRemoteAddr();

Upvotes: 15

Related Questions