开发环境是 java+nginx+tomcat
获取ip的代码
private String getIpAddress(HttpServletRequest request) {
String ip = null;
String ipAddresses = request.getHeader("X-Forwarded-For");
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
ipAddresses = request.getHeader("Proxy-Client-IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
ipAddresses = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
ipAddresses = request.getHeader("HTTP_CLIENT_IP");
}
if (ipAddresses == null || ipAddresses.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
ipAddresses = request.getHeader("X-Real-IP");
}
if (ipAddresses != null && ipAddresses.length() != 0) {
ip = ipAddresses.split(",")[0];
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ipAddresses)) {
ip = request.getRemoteAddr();
}
return ip;
}
但是请求返回的都是127.0.0.1 后来发现是nginx反向代理的原因,在nginx中加入下面这行代码, 重载nginx配置就可以了
proxy_set_header x-forwarded-for $remote_addr;
server {
listen 8117;
server_name localhost;
location / {
proxy_pass http://127.0.0.1:8088;
proxy_set_header x-forwarded-for $remote_addr;
}
}