Pages

Footer Pages

Spring Boot

Java String API

Java Conversions

Kotlin Programs

Kotlin Conversions

Java Threads Tutorial

Java 8 Tutorial

Wednesday, November 18, 2020

How To Get Client IP Address In Java Servlets

1. Overview

In this quick tutorial, you'll learn how to get the client ip address when a request comes to server. But, this can be done only in the java servlet application.

Simply, you can call directly on the request object as "request.getRemoteAddr()" on the javax.servlet.http.HttpServletRequest object.

How To Get Client IP Address In Java Servletsq


2. Example to get the client ip address

let us create a simple web application that gets the request and repose objects but we are interested in only request object. 

Because, all the values from client are part of HTTP request.

Actually, calling getRemoteAddr() method does not get the correct ip address of client in some cases.

In those scenarios might be client ip address is forwarded by the proxies. Mostly the client ip is present in the http header property "X-FORWARDED-FOR". we need to just get this property. If this value is null then get the value from getRemoteAddr() method.

This way gives the right ip address always. 

Created a separate method that to fetch the client ip address.

private static String getClientIpAddress(HttpServletRequest request) {

String remoteAddress = "";

if (request != null) {
    remoteAddr = request.getHeader("X-FORWARDED-FOR");
    if (remoteAddr == null || "".equals(remoteAddr)) {
        remoteAddress = request.getRemoteAddr();
    }
}

return remoteAddress;

3. "X-FORWARDED-FOR" and getRemoteAddr() are not working

There are some cases where the combination of these two "X-FORWARDED-FOR" and getRemoteAddr() method does work.

To correct the property, first need to look into the all properties of HTTP header. 

First, use request.getHeaderNames() method to get all header properties or keys.

Next, take each header key and get the corresponding values from the header using request.getHeader(headerKey) method.

Finally, print all the key and value pairs are in HTTP header.

private void printRequestHeadersKeyValues(HttpServletRequest request) {

    Map<String, String> result = new HashMap<>();

    Enumeration headerNames = request.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String headerKey = (String) headerNames.nextElement();
        String headerValue = request.getHeaderheaderKey;
        System.out.println(headerKey+" : "+headerValue)
    }

}

Output:

referer : https://www.google.com/,
cf-ipcountry : US,
cf-ray : 348c7acba8a02210-EWR,
x-forwarded-proto : https,
accept-language : en-US,en;q=0.8,
cookie : __cfduid=d39823749ksjfksdf90823r3298; _ga=GA1.2.450731937.1490726069,

x-forwarded-for : 106.8.189.76,  // <------ This is client real IP

accept : text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8,

x-real-ip : 187.343.987.123,  // <------ This is proxy IP

x-forwarded-server : testing.com,
x-forwarded-host : testing.com,
 cf-visitor : {\scheme\:\https\},
host : 127.0.0.1:8080,
upgrade-insecure-requests : 1,
connection : close,
cf-connecting-ip : 102.81.315.51,
accept-encoding : gzip,
user-agent :  Mozilla/24.0 (Macintosh; Intel Mac OS X 13_09_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3030.99 Safari/789.98

You can pick the right property from the above list which is having the correct client ip address.

4. Check for all Header Possible Candidates

Another way is get the all possible candidates that may get the client ip address
Just loop over this list and get values if any one is present in the header.

If nothing is having the value then take the value from getRemoteAddr() method.

Sample code but these header values can be modified with fake values.

private static final String[] VALID_IP_HEADER_CANDIDATES = { 
    "X-Forwarded-For",
    "Proxy-Client-IP",
    "WL-Proxy-Client-IP",
    "HTTP_X_FORWARDED_FOR",
    "HTTP_X_FORWARDED",
    "HTTP_X_CLUSTER_CLIENT_IP",
    "HTTP_CLIENT_IP",
    "HTTP_FORWARDED_FOR",
    "HTTP_FORWARDED",
    "HTTP_VIA",
    "REMOTE_ADDR" };

public static String getClientIpAddress(HttpServletRequest request) {
    for (String header : VALID_IP_HEADER_CANDIDATES) {
        String ipAddress = request.getHeader(header);
        if (ipAddress != null && ipAddress.length() != 0 && !"unknown".equalsIgnoreCase(ipAddress)) {
            return ipAddress;
        }
    }
    return request.getRemoteAddr();
}

5. Conclusion

In this short article, you've seen how to get the actual client ip address in java servlet application using getRemoteAddr() method and header keys.

Ref

HTTP Header

HTTP X header

how to set servlet session timeout?

No comments:

Post a Comment

Please do not add any spam links in the comments section.