码迷,mamicode.com
首页 > Windows程序 > 详细

c# 获取web客户端ip

时间:2016-06-07 16:22:12      阅读:319      评论:0      收藏:0      [点我收藏+]

标签:

       

 #region 获取web客户端ip

        /// <summary>
        /// 获取IP地址
        /// </summary>
        /// <returns></returns>
        public static string getIPAddress()
        {
            string ipv4 = String.Empty;
            foreach (IPAddress ip in Dns.GetHostAddresses(GetClientIP()))
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    ipv4 = ip.ToString();
                    break;
                }
            }
            if (ipv4 != String.Empty)
            {
                return ipv4;
            }
            // 利用 Dns.GetHostEntry 方法,由获取的 IPv6 位址反查 DNS 纪录,
            // 再逐一判断何者为 IPv4 协议,即可转为 IPv4 位址。
            foreach (IPAddress ip in Dns.GetHostEntry(GetClientIP()).AddressList)
            //foreach (IPAddress ip in Dns.GetHostAddresses(Dns.GetHostName()))
            {
                if (ip.AddressFamily.ToString() == "InterNetwork")
                {
                    ipv4 = ip.ToString();
                    break;
                }
            }
            return ipv4;
        }

 private static string GetClientIP()
        {
            if (null == HttpContext.Current.Request.ServerVariables["HTTP_VIA"])
            {
                return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            else
            {
                return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            }
        } 

 

    #endregion

c# 获取web客户端ip

标签:

原文地址:http://www.cnblogs.com/lk516924/p/5567168.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!