【问题标题】:How to get the public IP address of a user in C#如何在C#中获取用户的公共IP地址
【发布时间】:2013-10-17 15:13:09
【问题描述】:

我想要使用我网站的客户的公共 IP 地址。 下面的代码显示了局域网中的本地IP,但我想要客户端的公共IP。

//get mac address
NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces();
String sMacAddress = string.Empty;
foreach (NetworkInterface adapter in nics)
{
    if (sMacAddress == String.Empty)// only return MAC Address from first card  
    {
        IPInterfaceProperties properties = adapter.GetIPProperties();
        sMacAddress = adapter.GetPhysicalAddress().ToString();
    }
}
// To Get IP Address


string IPHost = Dns.GetHostName();
string IP = Dns.GetHostByName(IPHost).AddressList[0].ToString();

输出:

IP地址:192.168.1.7

请帮我获取公网IP地址。

【问题讨论】:

  • @Parker 虽然他的代码看起来像是重复的,但他确实是在询问 ASP.NET 并获取客户端地址,这是非常可行的。
  • 您好,您有什么理由在将近一年半之后不接受我的回答?如果你是故意这样做的,很高兴得到你的评论。谢谢。

标签: c# asp.net asp.net-mvc asp.net-mvc-4


【解决方案1】:

这是我用的:

protected void GetUser_IP()
{
    string VisitorsIPAddr = string.Empty;
    if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
    {
        VisitorsIPAddr = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
    }
    else if (HttpContext.Current.Request.UserHostAddress.Length != 0)
    {
        VisitorsIPAddr = HttpContext.Current.Request.UserHostAddress;
    }
    uip.Text = "Your IP is: " + VisitorsIPAddr;
}

“uip”是aspx页面中显示用户IP的标签名称。

【讨论】:

  • 对象引用未设置为对象的实例。 if (HttpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
  • 字符串方向 = ""; WebRequest request = WebRequest.Create("checkip.dyndns.org/"); using (WebResponse response = request.GetResponse()) using (StreamReader stream = new StreamReader(response.GetResponseStream())) { direction = stream.ReadToEnd(); } / /在html中搜索ip int first = direction.IndexOf("Address: ") + 9; int last = direction.LastIndexOf("
【解决方案2】:

您可以使用“HTTP_X_FORWARDED_FOR”或“REMOTE_ADDR”标头属性。

Machine Syntax blog .引用方法GetVisitorIPAddress

    /// <summary>
    /// method to get Client ip address
    /// </summary>
    /// <param name="GetLan"> set to true if want to get local(LAN) Connected ip address</param>
    /// <returns></returns>
    public static string GetVisitorIPAddress(bool GetLan = false)
    {
        string visitorIPAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];

        if (String.IsNullOrEmpty(visitorIPAddress))
            visitorIPAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

        if (string.IsNullOrEmpty(visitorIPAddress))
            visitorIPAddress = HttpContext.Current.Request.UserHostAddress;

        if (string.IsNullOrEmpty(visitorIPAddress) || visitorIPAddress.Trim() == "::1")
        {
            GetLan = true;
            visitorIPAddress = string.Empty;
        }

        if (GetLan && string.IsNullOrEmpty(visitorIPAddress))
        {
                //This is for Local(LAN) Connected ID Address
                string stringHostName = Dns.GetHostName();
                //Get Ip Host Entry
                IPHostEntry ipHostEntries = Dns.GetHostEntry(stringHostName);
                //Get Ip Address From The Ip Host Entry Address List
                IPAddress[] arrIpAddress = ipHostEntries.AddressList;

                try
                {
                    visitorIPAddress = arrIpAddress[arrIpAddress.Length - 2].ToString();
                }
                catch
                {
                    try
                    {
                        visitorIPAddress = arrIpAddress[0].ToString();
                    }
                    catch
                    {
                        try
                        {
                            arrIpAddress = Dns.GetHostAddresses(stringHostName);
                            visitorIPAddress = arrIpAddress[0].ToString();
                        }
                        catch
                        {
                            visitorIPAddress = "127.0.0.1";
                        }
                    }
                }

        }


        return visitorIPAddress;
    }

【讨论】:

  • 我在 Azure VM 上尝试过,arrIpAddress[0] 包含正确的 IPv6 地址 String,因此 Catch 没有执行,结果我们得到 IPv6 而不是本地 IPv4 或 127.0.0.1 . IPv4 保存在arrIpAddress[1] 中。在这种情况下,我该如何处理才能获得 IPv4?
【解决方案3】:

所有这些建议的组合,以及它们背后的原因。也可以随意添加更多测试用例。如果获取客户端 IP 至关重要,那么您可能希望得到所有这些都运行一些比较,结果可能更准确。

简单检查此线程中的所有建议以及我自己的一些代码...

    using System.IO;
    using System.Net;

    public string GetUserIP()
    {
        string strIP = String.Empty;
        HttpRequest httpReq = HttpContext.Current.Request;

        //test for non-standard proxy server designations of client's IP
        if (httpReq.ServerVariables["HTTP_CLIENT_IP"] != null)
        {
            strIP = httpReq.ServerVariables["HTTP_CLIENT_IP"].ToString();
        }
        else if (httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
        {
            strIP = httpReq.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
        }
        //test for host address reported by the server
        else if
        (
            //if exists
            (httpReq.UserHostAddress.Length != 0)
            &&
            //and if not localhost IPV6 or localhost name
            ((httpReq.UserHostAddress != "::1") || (httpReq.UserHostAddress != "localhost"))
        )
        {
            strIP = httpReq.UserHostAddress;
        }
        //finally, if all else fails, get the IP from a web scrape of another server
        else
        {
            WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
            using (WebResponse response = request.GetResponse())
            using (StreamReader sr = new StreamReader(response.GetResponseStream()))
            {
                strIP = sr.ReadToEnd();
            }
            //scrape ip from the html
            int i1 = strIP.IndexOf("Address: ") + 9;
            int i2 = strIP.LastIndexOf("</body>");
            strIP = strIP.Substring(i1, i2 - i1);
        }
        return strIP;
    }

【讨论】:

    【解决方案4】:

    该代码为您获取服务器的 IP 地址,而不是访问您网站的客户端的地址。将HttpContext.Current.Request.UserHostAddress 属性用于客户端的IP 地址。

    【讨论】:

      【解决方案5】:

      对于 Web 应用程序(ASP.NET MVC 和 WebForm)

      /// <summary>
      /// Get current user ip address.
      /// </summary>
      /// <returns>The IP Address</returns>
      public static string GetUserIPAddress()
      {
          var context = System.Web.HttpContext.Current;
          string ip = String.Empty;
      
          if (context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)
              ip = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
          else if (!String.IsNullOrWhiteSpace(context.Request.UserHostAddress))
              ip = context.Request.UserHostAddress;
      
          if (ip == "::1")
              ip = "127.0.0.1";
      
          return ip;
      }
      

      对于 Windows 应用程序(Windows 窗体、控制台、Windows 服务...)

          static void Main(string[] args)
          {
              HTTPGet req = new HTTPGet();
              req.Request("http://checkip.dyndns.org");
              string[] a = req.ResponseBody.Split(':');
              string a2 = a[1].Substring(1);
              string[] a3=a2.Split('<');
              string a4 = a3[0];
              Console.WriteLine(a4);
              Console.ReadLine();
          }
      

      【讨论】:

        【解决方案6】:

        这么多这些代码 sn-ps 真的很大,可能会使寻求帮助的新程序员感到困惑。

        这个简单紧凑的代码来获取访问者的 IP 地址怎么样?

        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"];
                }
        

        简单、简短、紧凑。

        【讨论】:

          【解决方案7】:

          我有一个扩展方法:

          public static string GetIp(this HttpContextBase context)
          {
              if (context == null || context.Request == null)
                  return string.Empty;
          
              return context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] 
                     ?? context.Request.UserHostAddress;
          }
          

          注意:“HTTP_X_FORWARDED_FOR”用于代理后面的 ip。 context.Request.UserHostAddress 与“REMOTE_ADDR”相同。

          但请记住,实际 IP 不是必需的。

          来源:

          IIS Server Variables

          Link

          【讨论】:

            【解决方案8】:

            我的版本同时处理 ASP.NET 或 LAN IP:

            /** 
             * Get visitor's ip address.
             */
            public static string GetVisitorIp() {
                string ip = null;
                if (HttpContext.Current != null) { // ASP.NET
                    ip = string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"])
                        ? HttpContext.Current.Request.UserHostAddress
                        : HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                }
                if (string.IsNullOrEmpty(ip) || ip.Trim() == "::1") { // still can't decide or is LAN
                    var lan = Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault(r => r.AddressFamily == AddressFamily.InterNetwork);
                    ip = lan == null ? string.Empty : lan.ToString();
                }
                return ip;
            }
            

            【讨论】:

              【解决方案9】:
               private string GetClientIpaddress()
                  {
                      string ipAddress = string.Empty;
                      ipAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                      if (ipAddress == "" || ipAddress == null)
                      {
                          ipAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
                          return ipAddress;
                      }
                      else
                      {
                          return ipAddress;
                      }
                  }
              

              【讨论】:

                【解决方案10】:

                在 MVC 5 上你可以使用这个:

                string cIpAddress = Request.UserHostAddress; //Gets the client ip address
                

                string cIpAddress = Request.ServerVariables["REMOTE_ADDR"]; //Gets the client ip address
                

                【讨论】:

                  【解决方案11】:

                  在MVC中IP可以通过以下代码获取

                  string ipAddress = Request.ServerVariables["REMOTE_ADDR"];
                  

                  【讨论】:

                  • 对象引用未设置为对象的实例。收到此错误
                  【解决方案12】:
                  string IP = HttpContext.Current.Request.Params["HTTP_CLIENT_IP"] ?? HttpContext.Current.Request.UserHostAddress;
                  

                  【讨论】:

                  • 最好提供您的解决方案的简要说明,以使答案更有价值
                  【解决方案13】:

                  就用这个........

                  public string GetIP()
                  {
                     string externalIP = "";
                     externalIP = (new WebClient()).DownloadString("http://checkip.dyndns.org/");
                     externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")).Matches(externalIP)[0].ToString();
                     return externalIP;
                  }
                  

                  【讨论】:

                  • 你不能在asp.net项目中使用它,因为总是返回服务器ip地址!
                  【解决方案14】:

                  我们连接到为我们提供外部 IP 地址的服务器,并尝试从返回的 HTML 页面中解析 IP。但是当服务器对这些页面进行小的更改或删除它们时,这些方法将无法正常工作。

                  这是一种使用已运行多年的服务器获取外部 IP 地址并快速返回简单响应的方法... https://www.codeproject.com/Tips/452024/Getting-the-External-IP-Address

                  Private string getExternalIp()
                  {
                  try
                  {
                      string externalIP;
                      externalIP = (new 
                      WebClient()).DownloadString("http://checkip.dyndns.org/");
                      externalIP = (new Regex(@"\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"))
                                   .Matches(externalIP)[0].ToString();
                      return externalIP;
                  }
                  catch { return null; }
                  }
                  

                  VB.NET

                  Imports System.Net
                  Private Function GetExternalIp() As String
                  Try
                      Dim ExternalIP As String
                      ExternalIP = (New WebClient()).DownloadString("http://checkip.dyndns.org/")
                      ExternalIP = (New Regex("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")) _
                                   .Matches(ExternalIP)(0).ToString()
                      Return ExternalIP
                  Catch
                      Return Nothing
                  End Try
                  

                  结束函数

                  【讨论】:

                    【解决方案15】:
                    lblmessage.Text =Request.ServerVariables["REMOTE_HOST"].ToString();
                    

                    【讨论】:

                    • 感谢您提供此代码 sn-p,它可能会提供一些有限的即时帮助。一个正确的解释would greatly improve 它的长期价值通过展示为什么这是一个很好的解决问题的方法,并将使它对未来有其他类似问题的读者更有用。请edit您的回答添加一些解释,包括您所做的假设。
                    【解决方案16】:

                    您可以在以下网址下载 xNet:https://drive.google.com/open?id=1fmUosINo8hnDWY6s4IV4rDnHKLizX-Hq

                    首先,你需要导入xNet,代码:

                    using xNet;
                    

                    代码:

                    void LoadpublicIP()
                    {
                        HttpRequest httprequest = new HttpRequest();
                        String HTML5 = httprequest.Get("https://whoer.net/").ToString();
                        MatchCollection collect = Regex.Matches(HTML5, @"<strong data-clipboard-target="".your-ip(.*?)</strong>", RegexOptions.Singleline);
                        foreach (Match match in collect)
                        {
                            var val = Regex.Matches(match.Value, @"(?<ip>(\d|\.)+)");
                            foreach (Match m in val)
                            {
                                richTextBox1.Text = m.Groups[2].Value;
                            }
                        }
                    }
                    

                    【讨论】:

                      猜你喜欢
                      • 1970-01-01
                      • 2018-10-22
                      • 2017-09-23
                      • 2023-03-19
                      • 2016-05-27
                      • 1970-01-01
                      • 1970-01-01
                      • 1970-01-01
                      • 2011-03-16
                      相关资源
                      最近更新 更多