How To Get Client IP Address In Servlet

SHARE & COMMENT :

The host name and IP address of the client requesting the servlet can be obtained using the HttpRequest object. In the following section we have a detailed java code to get clients address in a servlet. If the client uses proxy server , the real request to the servlet directly arrives from the proxy server and so it uses proxy IP address. Syntax of this method is java.lang.String getRemoteAddr()

Methods to get client IP address in a servlet

There are mainly two methods used to get the remote address or client address. They are as follows:

  • HttpServletRequest.getRemoteAddr(): This method returns the internet address of the client sending the request.
  • HttpServletRequestgetRemoteHost(): This returns the host name of the client sending the request. If the name is unknown then its returns an empty string.

Example

Example of getting clients address in a servlet:

Listing 1:ClientsAdd

import java.io.*;

import java.util.*;

import javax.servlet.*;

import javax.servlet.http.*;

public class ClientsAdd 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>");

  }
}

Execute ClientsAdd.java in Eclipse and an output on screen appears which displays IP address of your server.

Previous Tutorial : Servlet Filter || Next Tutorial : Cookies In Servlet

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better