Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 669
Bostone Avatar asked Dec 02 '09 22:12

Bostone


2 Answers

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

final String ip = getThreadLocalRequest().getRemoteAddr();
like image 52
Bostone Avatar answered Oct 04 '22 22:10

Bostone


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") 
like image 23
amanas Avatar answered Oct 04 '22 22:10

amanas