[转]C#如何获取客户端IP地址

代码如下:

    /// <summary>
    /// 获取客户端IP地址
   /// </summary>
    /// <returns></returns>
    public static string GetIPAddress()
    {
        string user_IP = string.Empty;
        if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
        {
            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
            {
                user_IP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else
            {
                user_IP = System.Web.HttpContext.Current.Request.UserHostAddress;
            }
        }
        else
        {
            user_IP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
        }
        return user_IP;
    }

 

posted @ 2013-08-12 08:51  Seasons1987  阅读(431)  评论(0编辑  收藏  举报