This is the complete solution, Just copy paste and run the code
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
@WebServlet("/ipaddress")
public class GetIpAddressServlet extends HttpServlet {
/**
* Author : Deepak Bajaj
*/
public static final long serialVersionUID = 1L;
// Below code is just to get the VALID IP Address headers
public static final String[] VALID_IP_HEADER_CANDIDATES = {
"X-Forwarded-For",
"Proxy-Client-IP",
"WL-Proxy-Client-IP",
"HTTP_X_FORWARDED_FOR",
"HTTP_X_FORWARDED",
"HTTP_X_CLUSTER_CLIENT_IP",
"HTTP_CLIENT_IP",
"HTTP_FORWARDED_FOR",
"HTTP_FORWARDED",
"HTTP_VIA",
"REMOTE_ADDR" };
// To get the client's IP Address
public static String GetIpAddressServlet(HttpServletRequest request) throws IOException, ServletException {
for (String header : VALID_IP_HEADER_CANDIDATES) {
String ip = request.getHeader(header);
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
}
}
return request.getRemoteAddr();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get the client's IP address
String clientIP = GetIpAddressServlet(request);
// Print or use the client's IP address as needed
System.out.println("Client IP Address: " + clientIP);
// You can send the IP address as a response to the client if needed
response.getWriter().write("Client IP Address: " + clientIP);
}
NOTE :-
Now just try to access your application over the remote client's machine http://IPofMachineWheretheCodeisHosted:PORT/ipaddress you will get the ip address of the remote client