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.
getLocalAddr() will return the IP-address of the request receiving system.
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.
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.
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/
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(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With