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
}
• 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. So you can get this by calling
String ipAddress = req.getHeader("X_FORWARDED_FOR");

No comments:

Post a Comment