In this short Java network article, I’d like to share some code examples which you can use to get IP address of a web client connecting to a Java web application. In practice, you need to get user’s IP address for the following reasons: logging, security, geolocation based on IP, etc.

Basically, you use the getRemoteAddr()method of HttpServletRequest class to get IP address of the connecting client. For example:

package net.codejava.ip;

import java.io.IOException;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.*;

@WebServlet("/url_mapping")
public class AppServlet extends HttpServlet {
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		String ipAddress = request.getRemoteAddr();
		
		// use ipAddress...
		
	}

}

On localhost, it will return IPv6 address like 0:0:0:0:0:0:0:1 or IPv4 address like 127.0.0.1. On the Internet, it will return an IP address of user’s ISP (Internet Service Provider). And in today’s cloud computing environment, your application usually sits behind a load balancer or gateway - So in such case, you need to use the following code:

String ipAddress = request.getHeader("X-FORWARDED-FOR");

This will return the real IP address of the client, which stored in the HTTP request header named X-FORWARDED-FOR. Otherwise, you’ll get address of the gateway or load balancer. Hence the proper code for getting IP address of a connecting client should be as follows:

String ipAddress = request.getHeader("X-FORWARDED-FOR");

if (ipAddress == null || ipAddress.isEmpty()) {
	ipAddress = request.getRemoteAddr();
}

In case you need to get user’s IP address in a Spring REST controller, just add a parameter of type HttpServletRequest in the handler method. For example:

package net.codejava.ip;

import javax.servlet.http.*;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/v1/users")
public class UserApiController {
	
	@GetMapping
	public List<User> listAll(HttpServletRequest request) {
		String clientIP = getClientIP(request);
		
		System.out.println("Client's IP Address: " + clientIP);
		
		// use IP Address...
		
		return repo.findAll();
	}	
	
	private String getClientIP(HttpServletRequest request) {
		String ip = request.getHeader("X-FORWARDED-FOR");
		
		if (ip == null || ip.isEmpty()) {
			ip = request.getRemoteAddr();
		}
		
		return ip;
	}
}

That’s how to get IP address of client in Java web application. I hope you find the code examples helpful. Thanks for reading.

 

Other Java Servlet Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Add comment