Getting IP address of client

Bhushan picture Bhushan · May 15, 2013 · Viewed 171.2k times · Source

I am developing a web application using JSP, Servlets (Container: Glassfish) in which I need to get clients IP Address.

I am getting the clients IP address, because I want to give access to some pages (like Customer maintenance forms) only on computers withing the office, I want to restrict access to those pages outside office.

Following is my code so far:

way1

String ipAddress =  request.getRemoteAddr();
System.out.println("IP Address: "+ipAddress);

way2

String ipAddress=null;
String getWay = request.getHeader("VIA");   // Gateway
ipAddress = request.getHeader("X-FORWARDED-FOR");   // proxy
if(ipAddress==null)
{
    ipAddress = request.getRemoteAddr();
}
System.out.println("IP Address: "+ipAddress);

Above code gives me different IP Address each time when I restart my computer (Shutdown->Start or Restart).

I am getting IP6 like:

fe80:0:0:0:20ca:1776:f5ff:ff15%13

Let me know what is wrong with this code?

Answer

Xavier Delamotte picture Xavier Delamotte · Feb 19, 2014

As @martin and this answer explained, it is complicated. There is no bullet-proof way of getting the client's ip address.

The best that you can do is to try to parse "X-Forwarded-For" and rely on request.getRemoteAddr();

public static String getClientIpAddress(HttpServletRequest request) {
    String xForwardedForHeader = request.getHeader("X-Forwarded-For");
    if (xForwardedForHeader == null) {
        return request.getRemoteAddr();
    } else {
        // As of https://en.wikipedia.org/wiki/X-Forwarded-For
        // The general format of the field is: X-Forwarded-For: client, proxy1, proxy2 ...
        // we only want the client
        return new StringTokenizer(xForwardedForHeader, ",").nextToken().trim();
    }
}