关于C#服务器端如何获取连接它的客户端的IP地址的问题

关于C#服务器端如何获取连接它的客户端的IP地址的问题,第1张

IPHostEntry ipe = Dns.GetHostEntry(Dns.GetHostName()) 

            IPAddress ipa = ipe.AddressList[1]

label.Text = ipa.Tostring()//看看是不是你想要的

只能根据用户请求带过来的sessionID所匹配的ip地址 而且只可以通过request获得ip 反正你能得到session 那得到request是一样简单的不是吗

得到request后命令为:

String ip = request.getRemoteAddr()

这个ip字符串就是了

#region 获取web客户端ip

        /// <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)

                        return System.Web.HttpContext.Current.Request.UserHostAddress

                    return CustomerIP

                }

                catch { }

                return userIP

           

        }

        #endregion


欢迎分享,转载请注明来源:夏雨云

原文地址:https://www.xiayuyun.com/zonghe/349293.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-08
下一篇2023-05-08

发表评论

登录后才能评论

评论列表(0条)

    保存