Asp.net MVC获取访问系统的客户端计算机的主机名和IP地址

 

string  HostName =  string .Empty;
string  ip =  string .Empty;
string  ipv4 = String.Empty;
 
if  (! string .IsNullOrEmpty(System.Web.HttpContext.Current.Request.ServerVariables[ "HTTP_VIA" ]))
      ip = Convert.ToString(System.Web.HttpContext.Current.Request.ServerVariables[ "HTTP_X_FORWARDED_FOR" ]);
if  ( string .IsNullOrEmpty(ip))
      ip = Request.UserHostAddress;
 
  // 利用 Dns.GetHostEntry 方法,由获取的 IPv6 位址反查 DNS 纪录,<br> // 再逐一判断何者为 IPv4 协议,即可转为 IPv4 位址。
foreach  (IPAddress ipAddr  in  Dns.GetHostEntry(ip).AddressList)
{
     if  (ipAddr.AddressFamily.ToString() ==  "InterNetwork" )
     {
         ipv4 = ipAddr.ToString();
     }
}
 
HostName =  "主机名: "  + Dns.GetHostEntry(ip).HostName +  " IP: "  + ipv4;

 在本机进行程序代码调试测试,其中字符串ip会显示为::1,是IPv6的IP地址格式,相当于127.0.0.1。最终处理成IPv4的显示地址。

-------------------------------------------------------------------------------------------------------------------------------------------------

上述方法,代码调试没有问题,但是放在服务器上后,客户端访问就出问题了,有部分电脑能获取主机名,但是ipv4显示为空,另外一部分

Dns.GetHostEntry(ip)中的ip正常,但是执行Dns.GetHostEntry(ip)貌似为null,导致出现异常。最后选择的方法是只记录客户端的IPV4,

复制代码
/// <summary>
        /// 获取web客户端ip
        /// </summary>
        /// <returns></returns>
        public static string GetWebClientIp()
        {

            string userIP = "未获取用户IP";

            try
            {
                if (System.Web.HttpContext.Current == null
                 || System.Web.HttpContext.Current.Request == null
                 || System.Web.HttpContext.Current.Request.ServerVariables == null)
                {
                    return "";
                }

                string CustomerIP = "";

                //CDN加速后取到的IP simone 090805
                CustomerIP = System.Web.HttpContext.Current.Request.Headers["Cdn-Src-Ip"];
                if (!string.IsNullOrEmpty(CustomerIP))
                {
                    return CustomerIP;
                }

                CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

                if (!String.IsNullOrEmpty(CustomerIP))
                {
                    return CustomerIP;
                }

                if (System.Web.HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
                {
                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                   
                    if (CustomerIP == null)
                    { 
                        CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; 
                    }
                }
                else
                {
                    CustomerIP = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                }

                if (string.Compare(CustomerIP, "unknown", true) == 0 || String.IsNullOrEmpty(CustomerIP))
                {
                    return System.Web.HttpContext.Current.Request.UserHostAddress;
                }
                return CustomerIP;
            }
            catch { }

            return userIP;

        }
复制代码
  1. public class CheckIP  
  2.    {  
  3.        #region 获取浏览器版本号  
  4.   
  5.        /// <summary>  
  6.        /// 获取浏览器版本号  
  7.        /// </summary>  
  8.        /// <returns></returns>  
  9.        public static string GetBrowser()  
  10.        {  
  11.            HttpBrowserCapabilities bc = HttpContext.Current.Request.Browser;  
  12.            return bc.Browser + bc.Version;  
  13.        }  
  14.  
  15.        #endregion  
  16.  
  17.        #region 获取操作系统版本号  
  18.   
  19.        /// <summary>  
  20.        /// 获取操作系统版本号  
  21.        /// </summary>  
  22.        /// <returns></returns>  
  23.        public static string GetOSVersion()  
  24.        {  
  25.            //UserAgent   
  26.            var userAgent = HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"];  
  27.   
  28.            var osVersion = "未知";  
  29.   
  30.            if (userAgent.Contains("NT 6.1"))  
  31.            {  
  32.                osVersion = "Windows 7";  
  33.            }  
  34.            else if (userAgent.Contains("NT 6.0"))  
  35.            {  
  36.                osVersion = "Windows Vista/Server 2008";  
  37.            }  
  38.            else if (userAgent.Contains("NT 5.2"))  
  39.            {  
  40.                osVersion = "Windows Server 2003";  
  41.            }  
  42.            else if (userAgent.Contains("NT 5.1"))  
  43.            {  
  44.                osVersion = "Windows XP";  
  45.            }  
  46.            else if (userAgent.Contains("NT 5"))  
  47.            {  
  48.                osVersion = "Windows 2000";  
  49.            }  
  50.            else if (userAgent.Contains("NT 4"))  
  51.            {  
  52.                osVersion = "Windows NT4";  
  53.            }  
  54.            else if (userAgent.Contains("Me"))  
  55.            {  
  56.                osVersion = "Windows Me";  
  57.            }  
  58.            else if (userAgent.Contains("98"))  
  59.            {  
  60.                osVersion = "Windows 98";  
  61.            }  
  62.            else if (userAgent.Contains("95"))  
  63.            {  
  64.                osVersion = "Windows 95";  
  65.            }  
  66.            else if (userAgent.Contains("Mac"))  
  67.            {  
  68.                osVersion = "Mac";  
  69.            }  
  70.            else if (userAgent.Contains("Unix"))  
  71.            {  
  72.                osVersion = "UNIX";  
  73.            }  
  74.            else if (userAgent.Contains("Linux"))  
  75.            {  
  76.                osVersion = "Linux";  
  77.            }  
  78.            else if (userAgent.Contains("SunOS"))  
  79.            {  
  80.                osVersion = "SunOS";  
  81.            }  
  82.            return osVersion;  
  83.        }  
  84.        #endregion  
  85.  
  86.        #region 获取客户端IP地址  
  87.   
  88.        /// <summary>  
  89.        /// 获取客户端IP地址  
  90.        /// </summary>  
  91.        /// <returns></returns>  
  92.        public static string GetIP()  
  93.        {  
  94.            string result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];  
  95.            if (string.IsNullOrEmpty(result))  
  96.            {  
  97.                result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];  
  98.            }  
  99.            if (string.IsNullOrEmpty(result))  
  100.            {  
  101.                result = HttpContext.Current.Request.UserHostAddress;  
  102.            }  
  103.            if (string.IsNullOrEmpty(result))  
  104.            {  
  105.                return "0.0.0.0";  
  106.            }  
  107.            return result;  
  108.        }  
  109.  
  110.        #endregion  
  111.  
  112.        #region 取客户端真实IP  
  113.   
  114.        ///  <summary>    
  115.        ///  取得客户端真实IP。如果有代理则取第一个非内网地址    
  116.        ///  </summary>    
  117.        public static string GetIPAddress  
  118.        {  
  119.            get  
  120.            {  
  121.                var result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];  
  122.                if (!string.IsNullOrEmpty(result))  
  123.                {  
  124.                    //可能有代理    
  125.                    if (result.IndexOf(".") == -1)        //没有“.”肯定是非IPv4格式    
  126.                        result = null;  
  127.                    else  
  128.                    {  
  129.                        if (result.IndexOf(",") != -1)  
  130.                        {  
  131.                            //有“,”,估计多个代理。取第一个不是内网的IP。    
  132.                            result = result.Replace("  """).Replace("'""");  
  133.                            string[] temparyip = result.Split(",;".ToCharArray());  
  134.                            for (int i = 0; i < temparyip.Length; i++)  
  135.                            {  
  136.                                if (IsIPAddress(temparyip[i])  
  137.                                        && temparyip[i].Substring(0, 3) != "10."  
  138.                                        && temparyip[i].Substring(0, 7) != "192.168"  
  139.                                        && temparyip[i].Substring(0, 7) != "172.16.")  
  140.                                {  
  141.                                    return temparyip[i];        //找到不是内网的地址    
  142.                                }  
  143.                            }  
  144.                        }  
  145.                        else if (IsIPAddress(result))  //代理即是IP格式    
  146.                            return result;  
  147.                        else  
  148.                            result = null;        //代理中的内容  非IP,取IP    
  149.                    }  
  150.   
  151.                }  
  152.   
  153.                string IpAddress = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != String.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["HTTP_X_REAL_IP"];  
  154.   
  155.                if (string.IsNullOrEmpty(result))  
  156.                    result = HttpContext.Current.Request.ServerVariables["HTTP_X_REAL_IP"];  
  157.   
  158.                if (string.IsNullOrEmpty(result))  
  159.                    result = HttpContext.Current.Request.UserHostAddress;  
  160.   
  161.                return result;  
  162.            }  
  163.        }  
  164.  
  165.        #endregion  
  166.  
  167.        #region  判断是否是IP格式  
  168.   
  169.        ///  <summary>  
  170.        ///  判断是否是IP地址格式  0.0.0.0  
  171.        ///  </summary>  
  172.        ///  <param  name="str1">待判断的IP地址</param>  
  173.        ///  <returns>true  or  false</returns>  
  174.        public static bool IsIPAddress(string str1)  
  175.        {  
  176.            if (string.IsNullOrEmpty(str1) || str1.Length < 7 || str1.Length > 15) return false;  
  177.   
  178.            const string regFormat = @"^d{1,3}[.]d{1,3}[.]d{1,3}[.]d{1,3}$";  
  179.   
  180.            var regex = new Regex(regFormat, RegexOptions.IgnoreCase);  
  181.            return regex.IsMatch(str1);  
  182.        }  
  183.  
  184.        #endregion  
  185.  
  186.        #region 获取公网IP  
  187.        /// <summary>  
  188.        /// 获取公网IP  
  189.        /// </summary>  
  190.        /// <returns></returns>  
  191.        public static string GetNetIP()  
  192.        {  
  193.            string tempIP = "";  
  194.            try  
  195.            {  
  196.                System.Net.WebRequest wr = System.Net.WebRequest.Create("http://city.ip138.com/ip2city.asp");  
  197.                System.IO.Stream s = wr.GetResponse().GetResponseStream();  
  198.                System.IO.StreamReader sr = new System.IO.StreamReader(s, System.Text.Encoding.GetEncoding("gb2312"));  
  199.                string all = sr.ReadToEnd(); //读取网站的数据  
  200.   
  201.                int start = all.IndexOf("[") + 1;  
  202.                int end = all.IndexOf("]", start);  
  203.                tempIP = all.Substring(start, end - start);  
  204.                sr.Close();  
  205.                s.Close();  
  206.            }  
  207.            catch  
  208.            {  
  209.                if (System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList.Length > 1)  
  210.                    tempIP = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()).AddressList[1].ToString();  
  211.                if (string.IsNullOrEmpty(tempIP))  
  212.                    return GetIP();  
  213.            }  
  214.            return tempIP;  
  215.        }  
  216.        #endregion  
  217.    }  
  1. /// <summary>  
  2.        /// 获取真ip  
  3.        /// </summary>  
  4.        /// <returns></returns>  
  5.        public  string GetRealIP()  
  6.        {  
  7.            string result = String.Empty;   
  8.            result = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];  
  9.            //可能有代理   
  10.            if (!string.IsNullOrWhiteSpace(result))  
  11.            {  
  12.                //没有"." 肯定是非IP格式  
  13.                if (result.IndexOf(".") == -1)  
  14.                {  
  15.                    result = null;  
  16.                }  
  17.                else  
  18.                {  
  19.                    //有",",估计多个代理。取第一个不是内网的IP。  
  20.                    if (result.IndexOf(",") != -1)  
  21.                    {  
  22.                        result = result.Replace(" "string.Empty).Replace("\""string.Empty);  
  23.   
  24.                        string[] temparyip = result.Split(",;".ToCharArray());  
  25.   
  26.                        if (temparyip != null && temparyip.Length > 0)  
  27.                        {  
  28.                            for (int i = 0; i < temparyip.Length; i++)  
  29.                            {  
  30.                                //找到不是内网的地址  
  31.                                if (IsIPAddress(temparyip[i]) && temparyip[i].Substring(0, 3) != "10." && temparyip[i].Substring(0, 7) != "192.168"&& temparyip[i].Substring(0, 7) != "172.16.")  
  32.                                {  
  33.                                    return temparyip[i];  
  34.                                }  
  35.                            }  
  36.                        }  
  37.                    }  
  38.                    //代理即是IP格式  
  39.                    else if (IsIPAddress(result))  
  40.                    {  
  41.                        return result;  
  42.                    }  
  43.                    //代理中的内容非IP  
  44.                    else  
  45.                    {  
  46.                        result = null;  
  47.                    }  
  48.                }  
  49.            }  
  50.   
  51.            if (string.IsNullOrWhiteSpace(result))  
  52.            {  
  53.                result = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];  
  54.            }  
  55.   
  56.            if (string.IsNullOrWhiteSpace(result))  
  57.            {  
  58.                result = System.Web.HttpContext.Current.Request.UserHostAddress;  
  59.            }  
  60.            return result;  
  61.        }  
  62.        public  bool IsIPAddress(string str)  
  63.        {  
  64.            if (string.IsNullOrWhiteSpace(str) || str.Length < 7 || str.Length > 15)  
  65.                return false;  
  66.   
  67.            string regformat = @"^(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})";   
  68.            Regex regex = new Regex(regformat, RegexOptions.IgnoreCase);  
  69.   
  70.            return regex.IsMatch(str);  
  71.        } 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值