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.

  • String getRemoteAddr(): Returns the Internet Protocol (IP) address of the client or last proxy that sent the request. For HTTP servlets, same as the value of the CGI variable REMOTE_ADDR.

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();
  }
}


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

getRemoteAddr()
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.

1 thought on “getRemoteAddr() Method Example”

Leave a Comment

Your email address will not be published.