none
请问在asp.net中,如何获取客户端ip地址? RRS feed

全部回复

  •     public static string GetIPAddress()
        {
            System.Web.HttpContext context = System.Web.HttpContext.Current;
            string ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

            if (!string.IsNullOrEmpty(ipAddress))
            {
                string[] addresses = ipAddress.Split(',');
                if (addresses.Length != 0)
                {
                    return addresses[0];
                }
            }

            return context.Request.ServerVariables["REMOTE_ADDR"];
        }

        public static string GetIp()
        {
            string ip = System.Web.HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (string.IsNullOrEmpty(ip))
            {
                ip = System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            }
            return ip;
        }  

    从网上找的,都无效。

    2021年4月26日 2:26
  • 你好,

    请问你的客户端具体指的是什么,你想得到的是什么数据。如果你想获取本机的IP地址,你可以尝试下面的代码。

    public static string GetLocalIPAddress()
    {
        var host = Dns.GetHostEntry(Dns.GetHostName());
        foreach (var ip in host.AddressList)
        {
            if (ip.AddressFamily == AddressFamily.InterNetwork)
            {
                return ip.ToString();
            }
        }
        throw new Exception("No network adapters with an IPv4 address in the system!");
    }

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2021年4月27日 1:18
    版主
  • 是用户登录的地方的ip地址啊
    2021年4月27日 1:52
  • 你好,

    感谢您的反馈。

    我还是不太明白您的意思,鉴于这种情况,我建议你可以去下面的论坛去询问,应该可以获得更专业的答案。

    ASP.NET Forums

    此论坛只讨论与.net framework相关的语言技术以及IDE.

    如果以后有.net framework相关的问题,欢迎来提问。

    Best Regards,

    Jack


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    2021年4月27日 7:29
    版主