top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

How to Get client’s address and hostname in Servlet?

+4 votes
962 views
How to Get client’s address and hostname in Servlet?
posted Mar 12, 2015 by Roshni

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote
 
Best answer

In this example we are going to see how to get client’s address and hostname in a Servlet. Java offers a very convenient way to handle client and server information such as hostname ip address etc.

Getting a client’s address and hostname requires that you:

Get clients ip adfress using HttpServletRequest.getRemoteAddr().
Get clients hostname using HttpServletRequest.getRemoteHost().

Sample Code Snippet :

package com.javacodegeeks.snippets.enterprise;    
import java.io.IOException;
import java.io.PrintWriter;    
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class GetClientAddressAndHostnameInServlet extends HttpServlet {

    private static final long serialVersionUID = -2128122335811219481L;

    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {

        PrintWriter out = res.getWriter();
        res.setContentType("text/plain");

        // client's IP address
        String remoteAddr = req.getRemoteAddr();

        // client's hostname
        String remoteHost = req.getRemoteHost();

        out.write("remoteAddr = ");
        out.write(remoteAddr);
        out.write("n");
        out.write("remoteHost = ");
        out.write(remoteHost);
        out.close();
    }
}

Web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
  version="2.5">

    <display-name>JCG Snippets Web Project</display-name>

    <servlet>
        <servlet-name>JCG Snippets Application</servlet-name>
        <servlet-class>com.javacodegeeks.snippets.enterprise.GetClientAddressAndHostnameInServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>JCG Snippets Application</servlet-name>
        <url-pattern>/jcgservlet</url-pattern>
    </servlet-mapping>

</web-app>

URL:

http://myhost:8080/jcgsnippets/jcgservlet

Output:

remoteAddr = 127.0.0.1 remoteHost = mypc

answer Mar 16, 2015 by Karthick.c
...