Java.Servlet.How can I get the client’s IP address on the server?

🧠 How to Get the Client’s IP Address in a Servlet

✅ The basic way:

String ipAddress = request.getRemoteAddr();

request.getRemoteAddr() returns the IP address of the client making the request.

Example:

  • If you’re testing locally ➔ might be 127.0.0.1.
  • If a real client ➔ might be 192.168.x.x or even a public IP.

⚡ BUT! There’s a Trap: Reverse Proxies and Load Balancers

If your server is behind:

  • a reverse proxy (like Nginx),
  • a load balancer (like AWS ELB),

then getRemoteAddr() will just give you the proxy’s IP, not the real client’s IP!

😬 To handle this, you need to check the HTTP header:
"X-Forwarded-For"

You can do:

String ipAddress = request.getHeader("X-Forwarded-For");
if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
    ipAddress = request.getRemoteAddr();
}
  • "X-Forwarded-For" usually contains the original client IP.
  • If it’s missing, fallback to getRemoteAddr().

✅ Sometimes X-Forwarded-For can contain multiple IP addresses (comma-separated list), if the request went through multiple proxies.
In that case, the first IP is usually the client’s real IP:

if (ipAddress != null && ipAddress.contains(",")) {
    ipAddress = ipAddress.split(",")[0].trim();
}

🎯 Full Example: Safely Get Client IP Address

public class ClientIpServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        String ipAddress = request.getHeader("X-Forwarded-For");
        
        if (ipAddress == null || ipAddress.isEmpty() || "unknown".equalsIgnoreCase(ipAddress)) {
            ipAddress = request.getRemoteAddr();
        } else {
            // Handle multiple IPs if necessary
            if (ipAddress.contains(",")) {
                ipAddress = ipAddress.split(",")[0].trim();
            }
        }

        response.setContentType("text/plain");
        response.getWriter().println("Client IP Address: " + ipAddress);
    }
}

🚨 Important Caveats:

SituationWhat Happens
Localhost testingYou’ll often get 127.0.0.1 or ::1
Behind proxy/load balancerNeed to check X-Forwarded-For header
No proxy usedgetRemoteAddr() is enough
Malicious clientsCan fake X-Forwarded-For! Don’t trust blindly for security-critical stuff

🛠 Quick Summary:

TaskHow
Basic IP retrievalrequest.getRemoteAddr()
Correct IP behind proxiesCheck "X-Forwarded-For" header first
Multiple IPs in headerUse the first one
This entry was posted in Без рубрики. Bookmark the permalink.