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;
        }
    }
}
Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap