How do I get client IP and hostname in Servlet?

package org.kodejava.example.servlet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ClientAddressServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // Get client's IP address
        String clientIP = request.getRemoteAddr();

        // Get client's host name
        String clientHost = request.getRemoteHost();

        PrintWriter out = response.getWriter();
        out.println("IP  : " + clientIP);
        out.println("Host: " + clientHost);        

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);

How do I get IP address of localhost?

The example here show you how to get an IP or host address using the class. To get an instance of InetAddress we call a static method of this class, the method is getLocalHost(), which return the local host address. Next, to get the IP address we can call the getHostAddress() method.



public class IPAddressExample {
    public static void main(String[] args) {
        try {
            InetAddress address = InetAddress.getLocalHost();
            String ip = address.getHostAddress();

            System.out.println("IP Address = " + ip);
        } catch (UnknownHostException e) {

The result of this code snippet:

IP Address =