.NET ez 2011-11-29
在ASP.NET上,通常會使用 Request.ServerVariables["REMOTE_ADDR"]; 來取得用戶端的IP。
但是有可能會遇到一個問題,當用戶端是透過代理伺服器連入時,則IP會變成是代理伺服器的,而並非是真正的用戶端IP。
所以,我們必須使用另外的方式取得用戶端的IP Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
/// <summary> /// 取得客戶端真實IP Address /// </summary> protected string GetClientIP(){ string ip = null; if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString()==string.Empty || Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToUpper().IndexOf("UNKNOWN") > 0) { ip = Request.ServerVariables["REMOTE_ADDR"]; } else if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(",") > 0) { ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Substring(1, Request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(",") - 1); } else if (Request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(";") > 0) { ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Substring(1, Request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(";") - 1); } else { ip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; } return ip.Replace(' ', string.Empty); }
標籤: .NET