問題
使用 request取得Client IP
解決方法
於WebService or WebSite or ASP.NET Application:
using MyWebToolkit; string ip=MyWebToolkit.GetClientIP(this.Context);
.cs:
using System; using System.Text; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace MyWebToolkit { public static class MyWebToolkit { public static string GetClientIP(System.Web.HttpContext context) { string ip = null; if (string.IsNullOrEmpty(context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]) || Convert.ToString(context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]).Contains("UNKNOWN")) { ip = context.Request.ServerVariables["REMOTE_ADDR"]; } else if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(",") > 0) { ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Substring(1, context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(",") - 1); } else if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(";") > 0) { ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Substring(1, context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(";") - 1); } else { ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; } return ip.Replace(" ", string.Empty); } } }
沒有留言:
張貼留言