Way2Java

getRemoteAddr() Method Example

getRemoteAddr() method is defined in ServletRequest interface from javax.servlet package inherited by HttpServletRequest.

With this method, the servlet programmer can know the IP address of the client from which the request came.

Let us see what Java API says about this method.

The method getRemoteAddr() returns the IP address of the cleint as a string.

Let us see the output by writing a program.

HTML Program: ClientData.html



Enter Your Name

web.xml entry for ClientInformation servlet


  efgh
  ClientInformation



  efgh
  /jasmine

Servelet Program: ClientInformation.java

import javax.servlet.*; 
import javax.servlet.http.*;
import java.io.*; 

public class ClientInformation extends HttpServlet
{
  public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException
  {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();

    String str = req.getRemoteAddr();
    out.println("req.getRemoteAddr() :  " + str);

    out.close();
  }
}



Output screen of ClientData.html with text field filled up. Ofcourse, this does not have any relevance with the method getRemoreAddr() method
.


Output screen when submit button is clicked.

Observe, the IP address as 127.0.0.1

To know the name of the client system (not IP address), a separate program exists: getRemoteHost() Method Example.