Thursday 4 August 2011

How to get the client information in a Servlet?

The hostname and IP Address of the client requesting the servlet can be obtained using the HttpRequest object. The following example shows how to get client ip address and hostname from a Servlet:
// This method is called by the servlet container to process a GET request.
    public void doGet(HttpServletRequest req, HttpServletResponse resp)
 throws IOException {
    
        // Get client's IP address
        String ipAddress = req.getRemoteAddr(); // ip
    
        // Get client's hostname
        String hostname = req.getRemoteHost(); // hostname
    } 
A servlet can use getRemoteAddr() and getRemoteHost() to retrieve the client's IP Address and client's host name from a http requestion.
  • getRemoteAddr(): Returns the internet address of the client sending the request. When the client address is unknown, returns an empty string.
  • getRemoteHost(): Returns the host name of the client sending the request. If the name is unknown, returns an empty string. The fully qualified domain name (e.g. "xyzws.com") of the client that made the request. The IP address is returned if this cannot be determined.
If the client is using a proxy server, the real request to your servlets arrives from the proxy, and so you get the proxy's IP address.
Most proxy servers will send the request with an header like "x-forwarded-for", or something similar. That header will contain the 'real' IP address. Be aware that fortunately there are a lot of anonymous proxy servers and they do not pass any additional header (and sometimes they do not appear as proxy). For example,
// This method is called by the servlet container to process a GET request.
    public void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws IOException {
    
        // Get client's IP address
        String ipAddress = req.getHeader("x-forwarded-for");
        if (ipAddress == null) {
            ipAddress = req.getHeader("X_FORWARDED_FOR");
            if (ipAddress == null){
                ipAddress = req.getRemoteAddr();
            }
        }     

    } 

No comments:

Post a Comment