得到client真IP住址

时间:2020-12-24 09:28:14

1、引进的必要性log4j-1.2.14.jar

package org.ydd.test;

import java.util.Enumeration;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

/**
* @author coco
* @version
* 获取IP4
*/
public class IP4 {
private static final Logger log = Logger.getLogger(IP4.class);
/**
* 获取client真实IP地址(注意:假设通过Squid反向代理软件。需更改squid.conf配置文件forwarded_for项默认是为on。
* 否则获取到的IP为unknown)
* @param request
* @return
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static String getIpAddr(HttpServletRequest request) {
log.debug("===================================================="); if(log.isDebugEnabled()){
StringBuffer buf = new StringBuffer("all head info:\n");
Enumeration enumeration = request.getHeaderNames();
while(enumeration.hasMoreElements()){
Object head = enumeration.nextElement();
if(null != head){
String value = request.getHeader(String.valueOf(head));
buf.append(head + "=" + value + "\n");
}
}
log.debug(buf.toString());
} String ip = request.getHeader("x-forwarded-for");
log.debug("request.getHeader(\"x-forwarded-for\")=" + ip); if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
log.debug("request.getHeader(\"X-Forwarded-For\")=" + ip);
} if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
log.debug("request.getHeader(\"Proxy-Client-IP\")=" + ip);
} if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
log.debug("request.getHeader(\"WL-Proxy-Client-IP\")=" + ip);
} if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
log.debug("request.getHeader(\"HTTP_CLIENT_IP\")=" + ip);
} if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
log.debug("request.getHeader(\"HTTP_X_FORWARDED_FOR\")=" + ip);
} if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
log.debug("request.getRemoteAddr()=" + ip);
} if(null != ip && ip.indexOf(',') != -1){
//假设通过了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串 IP 值
//取X-Forwarded-For中第一个非unknown的有效IP字符串
//如:X-Forwarded-For:192.168.1.110, 192.168.1.120, 192.168.1.130, 192.168.1.100
//用户真实IP为: 192.168.1.110
//注意:当訪问地址为 localhost 时 地址格式为 0:0:0:0:0:0:1
log.debug("ip=" + ip);
String[] ips = ip.split(",");
for (int i = 0; i < ips.length; i++) {
if(null != ips[i] && !"unknown".equalsIgnoreCase(ips[i])){
ip = ips[i];
break;
}
}
if("0:0:0:0:0:0:1".equals(ip)){
log.warn("因为client訪问地址使用 localhost,获取client真实IP地址错误,请使用IP方式訪问");
}
} if("unknown".equalsIgnoreCase(ip)){
log.warn("因为client通过Squid反向代理软件訪问,获取client真实IP地址错误,请更改squid.conf配置文件forwarded_for项默认是为on解决");
}
log.debug("====================================================");
return ip;
}
}

版权声明:本文博主原创文章。博客,未经同意不得转载。