日期:2014-05-19  浏览次数:20827 次

java 获取远程IP地址的问题?

代码如下:
Java code

     public String getIpAddr(HttpServletRequest request) { 
            String ip = request.getHeader("x-forwarded-for");    
            if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
                ip = request.getHeader("Proxy-Client-IP");    
            }    
            if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
                ip = request.getHeader("WL-Proxy-Client-IP");    
            }    
            if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {    
                ip = request.getRemoteAddr();    
            }    
            return ip;    
            }



在本地就可以的,但是上传到服务器 获得的不是真实的IP

这就为什么呢?

系统中有用户总就刷机,就是不断点击网站,现在想看下是哪里的IP访问的?

------解决方案--------------------
Java code

private String ip(HttpServletRequest req) {
        String ip = head(req, "X-Real-IP");
        if (ip != null && !"unknown".equalsIgnoreCase(ip)) {
            return ip;
        }
        ip = head(req, "X-Forwarded-For");
        if (ip != null && !"unknown".equalsIgnoreCase(ip)) {
            // 多次反向代理后会有多个IP值,第一个为真实IP。
            int index = ip.indexOf(',');
            return (index != -1) ? ip.substring(0, index) : ip;
        } else {
            return req.getRemoteAddr();
        }
    }
    
    private String head(HttpServletRequest req, String s){
        return req.getHeader(s);
    }

------解决方案--------------------
探讨

Java code

private String ip(HttpServletRequest req) {
String ip = head(req, "X-Real-IP");
if (ip != null && !"unknown".equalsIgnoreCase(ip)) {
return ip;
……