如何獲取終端使用者的真實ip

ybzshizds發表於2012-02-13
最近發現我們系統中獲取真實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 class="indent">

相關文章