配置了Nginx,Tomcat中的Web程序,获得的ip一直是“127.0.0.1”,比较纳闷。
获得远程ip,已经判断了很多情况,为什么会这样呢?


 正解

proxy_set_header        Host    $host;

 proxy_set_header        X-Real-IP       $remote_addr;

 proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;


 
 Java代码直接取:request.getRemoteAddr();

 再有Nginx等情况下,获得的地址不对,比如“127.0.0.1”。

/**
 * 
 2014年12月7日
 */
public class IpUtil {
 public static String getRemoteIp(HttpServletRequest request) {
 String remoteIp = request.getHeader("x-forwarded-for");
 if (remoteIp == null || remoteIp.isEmpty()
 || "unknown".equalsIgnoreCase(remoteIp)) {
 remoteIp = request.getHeader("X-Real-IP");
 }
 if (remoteIp == null || remoteIp.isEmpty()
 || "unknown".equalsIgnoreCase(remoteIp)) {
 remoteIp = request.getHeader("Proxy-Client-IP");
 }
 if (remoteIp == null || remoteIp.isEmpty()
 || "unknown".equalsIgnoreCase(remoteIp)) {
 remoteIp = request.getHeader("WL-Proxy-Client-IP");
 }
 if (remoteIp == null || remoteIp.isEmpty()
 || "unknown".equalsIgnoreCase(remoteIp)) {
 remoteIp = request.getHeader("HTTP_CLIENT_IP");
 }
 if (remoteIp == null || remoteIp.isEmpty()
 || "unknown".equalsIgnoreCase(remoteIp)) {
 remoteIp = request.getHeader("HTTP_X_FORWARDED_FOR");
 }
 if (remoteIp == null || remoteIp.isEmpty()
 || "unknown".equalsIgnoreCase(remoteIp)) {
 remoteIp = request.getRemoteAddr();
 }
 if (remoteIp == null || remoteIp.isEmpty()
 || "unknown".equalsIgnoreCase(remoteIp)) {
 remoteIp = request.getRemoteHost();
 }
 if (remoteIp != null && remoteIp.indexOf(",") != -1) {
 remoteIp = remoteIp.substring(remoteIp.lastIndexOf(",") + 1,
 remoteIp.length()).trim();
 }
 return remoteIp;
 }
}