How to get client's address in a servlet

This is detailed java code to get client's address in a servlet. In this example we have used method getremoteAddr() of the ServletRequest interface which returns IP address of the client in the string format.

How to get client's address in a servlet

How to get client's address in a servlet

     

This is detailed java code to get client's address in a servlet. In this example we have used method getremoteAddr() of the ServletRequest interface which returns IP address of the client in the string format.

Syntax of the method :  java.lang.String getRemoteAddr()

We have used a jsp page that is used to send a request to a servlet that execute the request and find the ID address of the client's request. Before run this code create a new directory named "user" in the tomcat-6.0.16/webapps and paste WEB-INF directory in same directory.

get_address.jsp

<%@page language="java" session="true" 
contentType="text/html;charset=ISO-8859-1" %> 
<b><font color="blue">Please Enter your Full Name here:</font></b><br>
<form name="frm" method="get" action="../user/GetAddress">
    <table border = "0">
        <tr align="left" valign="top">
            <td>First Name:</td>
            <td><input type="text" name ="name" /></td>
        </tr>
        <tr align="left" valign="top">
            <td></td>
            <td><input type="submit" name="submit" value="submit"/></td>
        </tr>
    </table>
</form>

Save this code as a .jsp file named "get_address.jsp" in the directory Tomcat-6.0.16/webapps/user/ and you can run this jsp page with following url in address bar of the browser "http://localhost:8080/user/get_address.jsp"

GetAddress.java

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class GetAddress extends HttpServlet {
  public void doGet(HttpServletRequest request,
HttpServletResponse response)
    throws IOException, ServletException{
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();    
    String name = request.getParameter("name");
	out.println("<h3>You have entered name : " + name + "<br>");	   
    out.println("<b><font color='blue'>
   IP Address of request : </font></b>"
	+request.getRemoteAddr()+"<h3>");
  }
}

Compile this java code and save .class file in directory C:\apache-tomcat-6.0.16\webapps\user\WEB-INF\classes.

web.xml

<servlet>
    <servlet-name>GetAddress</servlet-name>
    <servlet-class>GetAddress</servlet-class>
</servlet> 
<servlet-mapping>
    <servlet-name>GetAddress</servlet-name>
    <url-pattern>/GetAddress</url-pattern>
</servlet-mapping>

This is web .xml file use to map servlet. When run jsp page in the browser.....

User enters first name and click on submit button.......

Download Source Code