| Java FAQ | ||
| JSP FAQ | ||
| Servlet FAQ | ||
XyzWs Servlet FAQ:
How to get the client information in a Servlet?
Printer-friendly version |
Mail this to a friend
|
Advertisement
|
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.
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();
}
}
}
|