我有一个使用基于REST的Web服务的Java Spring应用程序。该服务具有一个端点,该端点应捕获请求的IP地址,并将其发送到我的JSP以收集一些信息。我尝试了SO中的所有方法,但似乎总是得到相同的结果,即主机服务器的IP地址。相关的Java类是:
private static final String[] IP_HEADER_CANDIDATES = {
"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" };
public void doStuff(HttpServletRequest servletRequest, ...) {
//...
String ipAddress = getClientIpAddress(servletRequest);
servletRequest.setAttribute("ip", ipAddress);
//...
}
public static String getClientIpAddress(HttpServletRequest request) {
for (String header : IP_HEADER_CANDIDATES) {
String ip = request.getHeader(header);
if (ip != null && ip.length() != 0 && !"unknown".equalsIgnoreCase(ip)) {
return ip;
}
}
return request.getRemoteAddr();
}
当我转发到我的JSP并调用console.log("${ip}");
时,我总是看到运行我的应用程序的docker的IP地址(基本上是localhost)。当我将代码部署到部署服务器时,看到的IP地址未反映我ifconfig中的IP地址(我正在公司VPN上测试此终结点,以为该代码不应该检测到任何代理?)。我不能正确捕获IP吗?