-1

I was reading that "With every Request to your web application, client's IP is sent too. So all you need to do is to have Filter over Requests and you can store the IP. "

If this is so,how can I do this ? I mean what is the method that can tell me the IP sent in the request ?

saplingPro
  • 20,769
  • 53
  • 137
  • 195
  • where were you reading that and what have you tried so far? – dokaspar Sep 07 '12 at 09:28
  • possible duplicate of [Is it possible to accurately determine the IP address of a client in java servlet](http://stackoverflow.com/questions/9326138/is-it-possible-to-accurately-determine-the-ip-address-of-a-client-in-java-servle) – Don Roby Sep 07 '12 at 09:29
  • @Dominik in the answer to http://stackoverflow.com/questions/12242915/need-to-obtain-the-public-ip-of-the-user-but-getting-the-ip-of-the-server-where – saplingPro Sep 07 '12 at 09:29

1 Answers1

2

Create a Filter class that implements javax.servlet.Filter, and fetch the IP from ServletRequest using getRemoteAddr():

public final class ExtractIpFilter implements Filter {
    private FilterConfig filterConfig = null;

    public void init(FilterConfig filterConfig) throws ServletException {
        this.filterConfig = filterConfig;
    }
    public void destroy() {
        this.filterConfig = null;
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
         throws IOException, ServletException {
      String ip = request.getRemoteAddr();
      // do something with the IP
   }
}

If your client is behind a proxy, try using request.getHeader("x-forwarded-for") instead, though this may or may not work depending on the configuration of the proxy.

João Silva
  • 89,303
  • 29
  • 152
  • 158