🧠 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.xor 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:
| Situation | What Happens |
|---|---|
| Localhost testing | You’ll often get 127.0.0.1 or ::1 |
| Behind proxy/load balancer | Need to check X-Forwarded-For header |
| No proxy used | getRemoteAddr() is enough |
| Malicious clients | Can fake X-Forwarded-For! Don’t trust blindly for security-critical stuff |
🛠 Quick Summary:
| Task | How |
|---|---|
| Basic IP retrieval | request.getRemoteAddr() |
| Correct IP behind proxies | Check "X-Forwarded-For" header first |
| Multiple IPs in header | Use the first one |