我正在使用以下代码(从另一篇文章How do I get the remote address of a client in servlet?复制)来获取客户端IP地址以及代理服务器(在PCF中部署的SpringBoot Appln)。
public static String getClientIpAddr(HttpServletRequest request)
{
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getRemoteAddr();
}
return ip;
}
request.getHeader(“ X-Forwarded-For”); /request.getRemoteAddr(); (从本地运行时)会产生预期的结果。我真的不明白其他条件的用法。
我觉得以下代码足以获取客户端IP地址和代理服务器(前提是我将Spring Boot与嵌入式tomcat结合使用并在PCF中部署代码)。您能确认吗?
private static String getClientIpAddr(HttpServletRequest httpRequest)
{
String clientIp = httpRequest.getHeader("X-Forwarded-For");
if (clientIp == null || clientIp.length() == 0)
{
clientIp = httpRequest.getRemoteAddr();
}
return clientIp;
}
答案 0 :(得分:0)
您可能想要这样的东西。
public class HttpRequestHelper {
private static final String[] HEADERS= {"X-Forwarded-For", "Proxy-Client-IP", "WL-Proxy-Client-IP", "HTTP_CLIENT_IP", "HTTP_X_FORWARDED_FOR"};
public static String getClientIpAddr(HttpServletRequest request) {
for (String header : HEADERS) {
String ip = request.getHeader(header);
if (ip != null && ip.length() > 0) {
return StringUtils.commaDelimitedListToStringArray(ip)[0];
}
}
return request.getRemoteAddr();
}
}
这将尝试按给定顺序的所有标头,如果存在则返回该标头。否则它将回退到request.getRemoteAddr()
。用更少的if
语句即可达到相同的效果。
我还考虑了X-Forwarded-For
标头中可能存在多个ip地址的情况。它将始终返回已解析数组中的第一个元素。