Get the IP address of the client connecting to a Servlet

Call the method getRemoteAddr on the HttpServletRequest instance.

MainServlet.java:

import javax.servlet.http.*;
import javax.servlet.*;
 
import java.io.*;
 
public class MainServlet extends HttpServlet
{
   public void doGet (HttpServletRequest request,
                      HttpServletResponse response)
      throws ServletException, IOException
   {
      String ip = request.getRemoteAddr();
      
      response.setContentType("text/html");
      PrintWriter out = response.getWriter();
 
      out.println("<html><body>");
      out.println(ip);
      out.println("</body></html>");
      out.close();
   }
}