I am trying to develop a Java web application (Servlet) which I need to get clients IP address.
Please do not considers this as a duplicate question because I tried all the possible answers that are available in the stackoverflow.
Following is my code so far:
1)
String ipAddress = request.getRemoteAddr();
In this case most of the tome I get the 'Default gateway adress'(147.120.1.5). not my machine ip address(174.120.100.17).
2)
String ipAddress = request.getHeader("X-FORWARDED-FOR");
if (ipAddress == null) {
ipAddress = request.getRemoteAddr();
}
In this case most of the tome I get the 'Default gateway adress'(147.120.1.5). not my machine ip address(174.120.100.17).
3)
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. Please make an answer.
Thank you very much.
解决方案
Try this one,
String ipAddress = request.getHeader("X-FORWARDED-FOR");
if (ipAddress == null) {
ipAddress = request.getRemoteAddr();
}