Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get client Ip Address in Java HttpServletRequest

Tags:

java

servlets

ip

I am trying to develop a Java web application (Servlet) which I need to get clients IP address.

Following is my code so far:

String ipAddress =  request.getRemoteAddr(); 

In this case most of the time I get the 'Default gateway address' (147.120.1.5). Not my machine IP address(174.120.100.17).

String ipAddress = request.getHeader("X-FORWARDED-FOR");   if (ipAddress == null) {       ipAddress = request.getRemoteAddr();   }  

In this case most of the time I get the 'Default gateway address' (147.120.1.5). Not my machine IP address (174.120.100.17).

InetAddress IP=InetAddress.getLocalHost(); System.out.println(IP.getHostAddress()); 

In this case I got the server IP Address (147.120.20.1).

My IP address in 147.120.100.17. Now I don't know how to get the real client IP address.

Thank you very much.

like image 724
Samith Dilshan Avatar asked Apr 28 '15 04:04

Samith Dilshan


People also ask

Which method returns the client IP address from ServletRequest?

getLocalAddr() will return the IP-address of the request receiving system.

How do I find the IP address of a Web application?

The simplest way to determine the IP address of a website is to use our DNS Lookup Tool. Simply go to the DNS Lookup Tool, type the website URL into the text entry, and select Lookup. You'll notice the search yielded a list of IPv4 addresses that differ from the IPs shown using the other methods.

How do I find my IP address on REST API?

Assuming you are making your "web service" with servlets, the rather simple method call . getRemoteAddr() on the request object will give you the callers IP address.


2 Answers

Try this one,

String ipAddress = request.getHeader("X-FORWARDED-FOR");   if (ipAddress == null) {       ipAddress = request.getRemoteAddr();   } 

reference : http://www.mkyong.com/java/how-to-get-client-ip-address-in-java/

like image 120
gihan-maduranga Avatar answered Sep 30 '22 21:09

gihan-maduranga


Try this one. for all condition

private static final String[] HEADERS_TO_TRY = {             "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" };  private String getClientIpAddress(HttpServletRequest request) {     for (String header : HEADERS_TO_TRY) {         String ip = request.getHeader(header);         if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {             return ip;         }     }      return request.getRemoteAddr(); } 
like image 45
elaheh aghaee Avatar answered Sep 30 '22 23:09

elaheh aghaee