c#使用WebRequest获取外部IP需要很长时间

时间:2016-09-17 19:39:36

标签: c#

我的方法:它基本上返回extern IPadress

public static string Get_IP()
{
    string url = "http://checkip.dyndns.org";
    WebRequest req = WebRequest.Create(url);
    WebResponse resp = req.GetResponse();
    StreamReader sr = new StreamReader(resp.GetResponseStream());
    string response = sr.ReadToEnd().Trim();
    string[] a = response.Split(':');
    string a2 = a[1].Substring(1);
    string[] a3 = a2.Split('<');
    string a4 = a3[0];
    return a4;
}

我无法理解为什么我的方法需要很长时间才能加载IpAdress,有时它会立即返回!

ps:我检查了我的互联网连接,它完美运行,我不认为它是连接速度问题!

谢谢!

1 个答案:

答案 0 :(得分:2)

使用这段代码,它将会很快

           string externalip = new WebClient().DownloadString("http://icanhazip.com");
           Console.WriteLine(externalip);