在做日志模块的时候,需要知道访问客户端的ip地址。起初用了
request.getRemoteAddr();
当时是在本地测试,取到的地址都是127.0.0.1或者是0:0:0:0:0:0:0:1。都是本机地址,一个是ipv4一个是ipv6,没在意。后来部署到阿里云之后发现也是同样的问题。开始怀疑是不是方法写的有问题。于是又百度到了新的方法。
/***
* 获取客户端IP地址;这里通过了Nginx获取;X-Real-IP,
* @param request
* @return
*/
public static String getClientIP(HttpServletRequest request) {
String fromSource = "X-Real-IP";
String ip = request.getHeader("X-Real-IP");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("X-Forwarded-For");
fromSource = "X-Forwarded-For";
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
fromSource = "Proxy-Client-IP";
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
fromSource = "WL-Proxy-Client-IP";
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
fromSource = "request.getRemoteAddr";
}
appLog.info("App Client IP: "+ip+", fromSource: "+fromSource);
return ip;
}
还是同样的结果。后来想到服务器配的是nginx + tomcat。nginx又是方向代理。监听80端口,映射本机tomcat的8080端口。在tomcat看来都是本地的80端口访问的,所以ip是localhost。于是在网上查找到了结果。nginx也需要配置几行,才能得到真实的ip地址。
location / {
proxy_pass http://127.0.0.1:8080/myweb/;
proxy_redirect off;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
}
参考链接:
http://greatwqs.iteye.com/blog/1946982