【问题标题】:how can i learn my client ip with .NET?如何使用 .NET 了解我的客户端 IP?
【发布时间】:2010-02-16 12:15:43
【问题描述】:

我需要来自 whatismyip.com 的客户端 IP。但我认为正则表达式模式不正确?你能帮我这个模式吗?

【问题讨论】:

  • 你为什么要使用 whatismyip.com 来检索你的 ip? :)
  • 投票结束。不要两次问同一个问题。如果您的问题没有给您答案,请尝试更详细地扩展它。 stackoverflow.com/questions/2272483/…
  • 对于它的价值,我相信我对你原来问题的回答应该可以解决问题:stackoverflow.com/questions/2272483/…
  • 是的,Jørns 对原始问题的回答是完全足够的。

标签: c# .net visual-studio network-programming


【解决方案1】:

你是否阅读了获得的 HTML 中的注释:

请将您的代码设置为抓取 你的IP来自 www.whatismyip.com/automation/n09230945.asp 有关更多信息,请参阅我们的 “推荐的自动化实践” 在论坛发帖。

所以这应该会让你继续前进:

using (var client = new WebClient())
{
    Console.WriteLine(client.DownloadString(
        "http://www.whatismyip.com/automation/n09230945.asp"));
}

【讨论】:

  • using 是一种自动删除变量使用的资源的好技术..
【解决方案2】:

使用 www.whatismyip.com 的自动化界面可以更轻松地实现这一点,因此不需要任何正则表达式:

static void Main(string[] args)
    {
        const string url = "http://www.whatismyip.com/automation/n09230945.asp";

        var client = new WebClient();
        try
        {
            var myIp = client.DownloadString(url);
            Console.WriteLine("Your IP: " + myIp);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error contacting website: " + ex.Message);
        }
    }

【讨论】:

    【解决方案3】:

    尝试使用
    http://www.whatismyip.org/
    这要简单得多。

    或者您想准确解析 whatismyip.com 的信息?

    【讨论】:

      【解决方案4】:

      改为这样:

      class Program
      {
          static void Main(string[] args)
          {
              string whatIsMyIp = "http://www.whatismyip.com/automation/n09230945.asp";
              WebClient wc = new WebClient();
              UTF8Encoding utf8 = new UTF8Encoding();
              string requestHtml = "";
              try
              {
                  requestHtml = utf8.GetString(wc.DownloadData(whatIsMyIp));
              }
              catch (WebException we)
              {
                  // do something with exception 
                  Console.Write(we.ToString());
              }
      
              IPAddress externalIp = null;
              externalIp = IPAddress.Parse(requestHtml);
      
              Console.Write("IP Numaram:" + externalIp.ToString());
              Console.ReadKey(); 
      
          }
      }
      

      【讨论】:

        【解决方案5】:

        这是您在 ASP.NET C# 中获取 ip 的方式

        string pstrClientAddress = HttpContext.Current.Request.UserHostAddress;
        

        【讨论】:

          猜你喜欢
          • 2012-12-03
          • 1970-01-01
          • 2017-01-26
          • 1970-01-01
          • 2022-07-27
          • 2011-05-31
          • 2021-07-07
          • 2013-05-09
          • 2021-09-15
          相关资源
          最近更新 更多