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();
}
}
}
Most Recent servlet Faqs
- How to get the client information in a Servlet?
- Can I control Session timeout?
- What is the difference between RequestDispatcher's forward method and HttpServletResponse's sendRedirect method?
- When do I use HttpSessionListener?
- What is the difference between the request attribute and request parameter?
- What is the defferent between getNamedDispatcher() and getRequestDispatcher()?
- How do you communicate in between applets and servlets?
Most Viewed servlet Faqs
- What is the difference between the request attribute and request parameter?(12100)
- When do I use HttpSessionListener?(11630)
- How to use ServletContext.getResourceAsStream(java.lang.String path)?(8250)
- What is the difference between RequestDispatcher's forward method and HttpServletResponse's sendRedirect method?(6881)
- Can I control Session timeout?(5294)
- What is the defferent between getNamedDispatcher() and getRequestDispatcher()?(4916)
- How to get the client information in a Servlet?(4477)