如何在Java HttpServletRequest中获取客户端IP地址 [英] How to get client Ip Address in Java HttpServletRequest
问题描述
我正在尝试开发一个Java Web应用程序(Servlet),我需要获取客户端的IP地址。
I am trying to develop a Java web application (Servlet) which I need to get clients IP address.
请不要将此视为重复的问题,因为我尝试了stackoverflow中可用的所有可能答案。
Please do not considers this as a duplicate question because I tried all the possible answers that are available in the stackoverflow.
以下是我的代码到目前为止:
1)
String ipAddress = request.getRemoteAddr();
在这种情况下,我得到的是默认网关地址(147.120.1.5)。不是我的机器IP地址(174.120.100.17)。
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();
}
在这种情况下,我获得了默认网关地址的大部分内容( 147.120.1.5)。不是我的机器IP地址(174.120.100.17)。
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());
在这种情况下,我得到了服务器IP地址(147.120.20.1)。
In this case I got the server IP Address(147.120.20.1).
我在147.120.100.17中的IP地址。现在我不知道如何获得真正的客户端IP地址。请回答。
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.
非常感谢。
推荐答案
试试这个,
String ipAddress = request.getHeader("X-FORWARDED-FOR");
if (ipAddress == null) {
ipAddress = request.getRemoteAddr();
}
参考: http://www.mkyong.com/java/how-to-get-client-ip-address- in-java /
这篇关于如何在Java HttpServletRequest中获取客户端IP地址的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!