getRemoteAddr() vs getRemoteHost()


Both getRemoteAddr() vs getRemoteHost() are defined in ServletRequest interface and serves the Servlet Programmer to retrieve the client system particulars from where the request came. They differ slightly in the output.

1. getRemoteAddr() returns a string containing the IP address (in format like IPiv, 127.0.0.1) of the client.

2. getRemoteHost() returns a string containing the name of the client system (like localhost or fully qualified name of the client).

Let us see what Java API says about these two methods as defined javax.servlet.ServletRequest interface.

  • public java.lang.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.
  • public java.lang.String getRemoteHost(): Returns the fully qualified name of the client or the last proxy that sent the request. If the engine cannot or chooses not to resolve the hostname (to improve performance), this method returns the dotted-string form of the IP address. For HTTP servlets, same as the value of the CGI variable REMOTE_HOST.
Example on getRemoteAddr() vs getRemoteHost(): Let us see the difference practically through 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 str1 = req.getRemoteAddr();
    out.println("req.getRemoteAddr() :  " + str1);

    String str2 = req.getRemoteHost();
    out.println("

req.getRemoteHost() : " + str2); out.close(); } }

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

getRemoteAddr() vs getRemoteHost()

The output screen when submit button is clicked.

getRemoteAddr() vs getRemoteHost()

Observe, the getRemoteAddr() returns the IP address as 127.0.0.1 and gerRemoteHost() returns localhost, the name given in ACTION attribute of FORM tag in HTML file.

Leave a Comment

Your email address will not be published.