Get Client IP address from HTTP Response in Java


In order to get the IP address of a Client you can make use of getRemoteAddr method from the HttpServletRequest class from javax.servlet.http package,

The tricky part here is there could be multiple headers the client might be behind the proxy servers or load balancers,

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * Java Program to get Client
 * IP address
 *
 * Author: Code2care.org
 * Date: 03-Apr-2022
 * Version: 1.0
 *
 */
public class JavaExample {

    public static void main(String[] args) throws UnknownHostException {
        System.out.println(getRemoteClientIPAddress());
    }

    private static String getRemoteClientIPAddress(HttpServletRequest request) {
        
        List<String> proxyHeadersList = new ArrayList();
        
        //There could be much more
        proxyHeadersList.add("X-Forwarded-FOR");
        proxyHeadersList.add("WL-Proxy-Client-IP");
        proxyHeadersList.add("Proxy-Client-IP");
        proxyHeadersList.add("HTTP_X_FORWARDED");
        String remoteIpAddress;
        
        for(String proxyHeader: proxyHeadersList) {
            remoteIpAddress = request.getHeader("X-FORWARDED-FOR");
            if (isValidIP(remoteIpAddress)) {
                return remoteIpAddress;
            }
        }

        return request.getRemoteAddr();
        
    }
    
    public static boolean isValidIP(String remoteIpAddress) {
        if (remoteIpAddress == null || "".equals(remoteIpAddress)) {
            return false;
        } else {
            return true;
        }
    }
}
Advertisements
Try Out Code2care Dev Tools:

Advertisements

Advertisements
Code2care is an initiative to publish and share varied knowledge in programming and technical areas gathered during day-to-day learnings and development activities.

Students and software developers can leverage this portal to find solutions to their various queries without re-inventing the wheel by referring to our easy to understand posts. Technical posts might include learnings, tutorials, trouble-shooting steps, video tutorials, code snippets, how-to, blogs, articles, etc.

🎉 We are celebrating the 10th years of Code2care! Thank you for all your support!

We strongly support Gender Equality & Diversity.