【问题标题】:Get Client Ip while submit a form. (ASP.net C#)提交表单时获取客户端 IP。 (ASP.net C#)
【发布时间】:2014-03-29 06:53:32
【问题描述】:

当用户在我的站点中提交表单时,我想获取客户端 IP。 我尝试使用该命令:Request.UserHostAddress

但我得到的不是 ip:::1

我该怎么办?

谢谢!

【问题讨论】:

  • 这是 UserHostaddress,假设您在本地运行项目。
  • 谢谢!它在服务器上工作

标签: c# asp.net visual-studio-2010


【解决方案1】:

那是因为您在本地进行测试。 ::1 是与127.0.0.1 等效的 IPv6。

What is IP address '::1'?

【讨论】:

    【解决方案2】:

    ::1localhost 相同

    在 ASP.NET 中,您可以这样做来获取用户 IP 地址

    public static string GetUserIpAddress()
    {
        string ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
        if (string.IsNullOrEmpty(ip))
        {
            ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
            if (ip == "::1") ip = "127.0.0.1"; // localhost
        }
        return ip;
    }
    

    【讨论】:

      【解决方案3】:

      您可以使用 REMOTE_ADDR,但如果您在本地访问该站点,它可能不起作用,它将显示本地主机。下面的代码会帮助你

              string clientIp = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
           if( !string.IsNullOrEmpty(clientIp) ) 
      {
            string[] forwardedIps = clientIp.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries );
            clientIp = forwardedIps[forwardedIps.Length - 1];
           } 
      else {
            clientIp = context.Request.ServerVariables["REMOTE_ADDR"];
           }
      

      【讨论】:

        【解决方案4】:

        ::1 是一个 IPv6 环回地址。这意味着127.0.0.1

        Ipv4  127.0.0.1    localhost
        Ipv6  ::1          localhost
        

        localhost

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-03-27
          • 1970-01-01
          • 2018-02-13
          • 1970-01-01
          • 2020-12-08
          • 1970-01-01
          • 2011-06-12
          • 1970-01-01
          相关资源
          最近更新 更多