如何获取终端用户的真实ip

12-02-13 ybzshizds
最近发现我们系统中获取真实ip和http://www.ip138.com/获取到的不一样,当然这只是少部分不一样,绝大多数获取到的还是一样的,以下是我们获取ip的实现代码,不知道有什么不合理的地方,还望请高人指点。谢谢!

/** 
	    * 获得客户端真实IP地址 
	    * @[author]param[/author] request 
	    * @return 
	    */ 
public static String getIpAddr(HttpServletRequest request) { 
	    	String ip = request.getHeader("X-Forwarded-For");
	    	ip = getTrueIp(ip);
	    	
	    	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	    		ip = request.getHeader("Proxy-Client-IP");
	    		ip = getTrueIp(ip);
	    	}
	    	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	    		ip = request.getHeader("WL-Proxy-Client-IP");
	    		ip = getTrueIp(ip);
	    	}
	    	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	    		ip = request.getHeader("HTTP_CLIENT_IP");
	    		ip = getTrueIp(ip);
	    	}
	    	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	    		ip = request.getHeader("HTTP_X_FORWARDED_FOR");
	    		ip = getTrueIp(ip);
	    	}
	    	if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
	    		ip = request.getRemoteAddr();
	    		ip = getTrueIp(ip);
	    	}
	    	return ip; 
	    }


/**
	     * 取真实客户端IP,过滤代理IP
	     * @[author]param[/author] ip
	     * @return
	     */
	    public static String getTrueIp(String ip){
	    	if(ip == null || "".equals(ip))return null;
	    	if(ip.indexOf(",") != -1)
	    	{
	    		String[] ipAddr = StringUtil.split(ip, ",");
	    		for(int i=0; i<ipAddr.length; i++)
	    		{
	    			if(isIp(ipAddr[i].trim()) 
	    					&& !ipAddr[i].trim().startsWith("10.")
	    					&& !ipAddr[i].trim().startsWith("172.16"))return ipAddr[i].trim();
	    		}
	    	}else{
	    		if(isIp(ip.trim())
	    				&& !ip.trim().startsWith("10.")
    					&& !ip.trim().startsWith("172.16"))
	    			return ip.trim();
	    	}
	    	return null;
	    }
<p>

猜你喜欢