java 获取ip

/**
	 * Purpose:获取ip
	 * @author Hermanwang
	 * @param request
	 * @return
	 * @throws Exception
	 * @return String
	 */
	public static String getClientIP(ServletRequest request) throws Exception{
    	//通過代理軟件無法獲取真實IP,所以先取得Header,判斷是否有用代理
    	String[] httpHeaders = new String[]{"x-forwarded-for", "Proxy-Client-clientIP", "WL-Proxy-Client-clientIP"};
    	String clientIP = null;
	    try {
	    	for (int i = 0; i < httpHeaders.length; i++) {
	    		clientIP = ((HttpServletRequest) request).getHeader(httpHeaders[i]);  
			    if(StringUtils.hasText(clientIP) && !clientIP.equalsIgnoreCase("unknown")){
			    	break;
			    }
	    	}
		    if(!StringUtils.hasText(clientIP) || clientIP.equalsIgnoreCase("unknown"))  {
		    	clientIP = request.getRemoteAddr();  
		    }

		}catch (Exception e) {
			throw e;
		}
	    return clientIP;
	}
阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页