asp.netクライアントIPアドレス、ブラウザタイプおよびバージョン番号、および使用するプラットフォーム名を取得

2342 ワード

    /// 
    ///      IP  (    )
    /// 
    ///           
    public static string GetHostAddress()
    {
        if (System.Web.HttpContext.Current == null || System.Web.HttpContext.Current.Request == null || System.Web.HttpContext.Current.Request.ServerVariables == null)
            return "";
        string userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
        if (string.IsNullOrEmpty(userHostAddress))
        {
            if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                userHostAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
        }
        if (string.IsNullOrEmpty(userHostAddress))
        {
            userHostAddress = HttpContext.Current.Request.UserHostAddress;
        }

        //          ,   IP     (         )
        if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress))
        {
            return userHostAddress;
        }
        return "127.0.0.1";
    }


    /// 
    ///   IP    
    /// 
    /// 
    /// 
    public static bool IsIP(string ip)
    {
        return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$");
    }

    /// 
    ///            
    /// 
    /// 
    public string GetClientBrowserVersions()
    {
        string browserVersions = string.Empty;
        HttpBrowserCapabilities hbc = HttpContext.Current.Request.Browser;
        string browserType = hbc.Browser.ToString();     //       
        string browserVersion = hbc.Version.ToString();    //     
        browserVersions = browserType + browserVersion;
        return browserVersions;
    }


    /// 
    ///             
    /// 
    /// 
    public string GetClient()
    {
        string browserClient = string.Empty;
        HttpBrowserCapabilities hbc = HttpContext.Current.Request.Browser;
        string patform = hbc.Platform;     //                 
        browserClient = patform;
        return browserClient;
    }