How to get client Ip Address in Java

In Java, you can use HttpServletRequest.getRemoteAddr() to get the client’s IP address that’s accessing your Java web application.


import javax.servlet.http.HttpServletRequest;

String ipAddress = request.getRemoteAddr();

1. Proxy Server or Cloudflare

For web application which is behind a proxy server, load balancer or the popular Cloudflare solution, you should get the client IP address via the HTTP request header X-Forwarded-For (XFF).


import javax.servlet.http.HttpServletRequest;

	//...
	
	private static String getClientIp(HttpServletRequest request) {

        String remoteAddr = "";

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

        return remoteAddr;
    }
	

2. Not working still?

Review the client’s HTTP request header, and try to identify where the IP address is stored.


    private Map<String, String> getRequestHeadersInMap(HttpServletRequest request) {

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

        Enumeration headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            String value = request.getHeader(key);
            result.put(key, value);
        }

        return result;
    }

Sample request headers for web application behind Cloudflare.


    "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=d3c6e5d73aa55b6b42fad9600c94849851490726068; _ga=GA1.2.450731937.1490726069",

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

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

    "x-real-ip" :"108.162.219.236",             // <------ This is cloudflare IP

    "x-forwarded-server" :"hostingcompass.com",
    "x-forwarded-host" :"hostingcompass.com",
     "cf-visitor" :"{\"scheme\":\"https\"}",
    "host" :"127.0.0.1:8080",
    "upgrade-insecure-requests" :"1",
    "connection" :"close",
    "cf-connecting-ip" :"100.8.204.40",
    "accept-encoding" :"gzip",
    "user-agent" : "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.87 Safari/537.36"
Note
Normally, before the web/proxy server forwards the request to the Java app server, it will store the real client IP request in a standard header name like x-forwarded-for, if you can't find the client IP in the entire request headers, try discussing it with your server administrator.

References

  1. Wiki X-Forwarded-For
  2. ServletRequest JavaDoc
  3. HttpServletRequest JavaDoc
  4. How to get Server IP address in Java

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider make a donation to these charities.

Comments

Leave a Reply

avatar
newest oldest most voted
Mass PR
Guest
Mass PR

Hi
I am getting some Private IP when I am trying to get my own IP. Its working fine in local but in production giving private IP instaed of My IP with the below code.
String ipAddress = request.getHeader(“X-FORWARDED-FOR”);
why it is giving different IP instead of my IP in Production.

Siva
Guest
Siva

i am getting output for the above code is 0:0:0:0:0:0:0:1, how to correct ip address from request object.

Marcos
Guest
Marcos

It works when deployed. On localhost it shows the 0:0:0:0:0:0:0:1 address you are seeing. Try it.

Justin James
Guest
Justin James

Please try with above code..

qingshan
Guest
qingshan

public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader(“X-Real-IP”);
if (null != ip && !””.equals(ip.trim())
&& !”unknown”.equalsIgnoreCase(ip)) {
return ip;
}
ip = request.getHeader(“X-Forwarded-For”);
if (null != ip && !””.equals(ip.trim())
&& !”unknown”.equalsIgnoreCase(ip)) {
// get first ip from proxy ip
int index = ip.indexOf(‘,’);
if (index != -1) {
return ip.substring(0, index);
} else {
return ip;
}
}
return request.getRemoteAddr();
}

dude
Guest
dude

X-FORWARDED-FOR is not safe because client can owerwrite it in request. Best solution is good configured proxy server.

disqus_pEBAlnoJps
Guest
disqus_pEBAlnoJps

Hi,

My setup is like

Squid reverse-proxy — sends request to–> Apache-server —.–> JBoss app server (using mod_jk)

I want to get the clients IP address in my java application, running in JBoss.

In my apache access.log, I can see the clients IP address (as the apache LogFormat is using X-Forwaded-For)

But

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

in Java returns NULL.

What could be the issue?

Could I be missing something in my mod_jk configuration ?

Thank you

mkyong
Guest
mkyong

Logs and review the entire request headers, to identify where the ip is stored.

P1P
Guest
P1P

Thanks ^^ It’s work for me.

askucins
Guest
askucins

Hmm… what about a case when that header has multiple IPs – this is a ‘legal’ case after all, even Wikipedia mentions that.

Would then that solution be applicable? (I’m under impression, that you’re assuming, that there is only one IP in that header).

Justin James
Guest
Justin James

Add this inside the try block:
InetAddress thisIp = InetAddress.getLocalHost();
out.println(“IP:” + thisIp.getHostAddress());

regards:

Hua
Guest
Hua

what if sb. spoof a XFF?

Vishal
Guest
Vishal

Nice. Thanks.!!

saurabh mittal
Guest
saurabh mittal

Hey Mkyong…i agree what you say about user behind the proxy server, but using “X-FORWARDED-FOR” didn’t help either. It is giving null. I am trying to get the real ip address of the client but its not working.
Only request.getRemoteAddr() gives some ip address but that ip address is not of the client its of the proxy server or the load balancer.

srinu
Guest
srinu

req.getHeader(“x-forwarded-for”);

Shubhrajyoti satpathy
Guest
Shubhrajyoti satpathy

hi srinu can u tell me how i shall be add this in project

trackback
How to get Server IP address in Java

[…] How to get client Ip Address in Java […]