import javax.servlet.http.HttpServletRequest;

public class RemoteAddress {

    public static String getRealClientIP(HttpServletRequest request) {
        String ip = request.getHeader("X-Forwarded-For");
        System.out.println(ip);
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
            System.out.println(ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
            System.out.println(ip);
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
            System.out.println(ip);
        }

        return ip;
    }
}

之前用如上代码测试都发现结果是127.0.0.1,用本机做服务器挂网上中转也是。以为是代码出现问题,后来直接挂到空间上,发现正常显示出外网了,于是用移动网访问本机服务器也可以正常显示IP了而不再是127.0.0.1或者::1 的IPv6的地址。

posted on 2015-02-12 08:56  Zempty  阅读(834)  评论(0编辑  收藏  举报