Your IP Address is: 216.73.216.124
Obtaining a site's visitor from a servlet or JSP is very simple. All
that is needed is to call the getRemoteAddr() method
defined in the HttpServletRequest interface.
An instance of a class implementing HttpServletRequest
is automatically passed to both the doGet() and doPost()
methods of the HttpServlet class.
The doGet() method for a Java servlet obtaining the
visitor's IP address would look something like this:
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{
String ipAddress = request.getRemoteAddr();
}
After calling request.getRemoteAddr(), the IP
address of the visitor will be stored in the ipAddress
String variable. We can then do whatever we need to do with it. The doPost()
method of a servlet obtaining the user's IP address would be nearly
identical to the doGet() method described above.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
{
String ipAddress = request.getRemoteAddr();
}
From a JSP, there is an implicit variable containing a class
implementing the HttpServletRequest interface. The name of
this implicit variable is, appropriately enough, request.
If we want to show the user their IP address (like we did in the
beginning of this file), this can be accomplished in a JSP with the
following code snippet: Your IP Address is:
<%=request.getRemoteAddr()%>.
If instead of just displaying it to the user, we need to store it in a variable, assign it to a field, or do anything else with it, we can obtain it from a JSP scriptlet:
<%
String ipAddress=request.getRemoteAddr();
%>
As can be seen from the above examples, obtaining a visitor's IP
address from a Java Servlet or JSP is trivial. Basically all that is
needed is to call the getRemoteAddr() method defined in the
HttpServletRequest interface. This method returns a String
containg the user's IP address.