Cru Dy Cru Dy - 2 months ago 23
C# Question

c# Get Extern IP using WebRequest Take a Long time

My Method : it basically return 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;
}


I Couldnt understand why My method take a long time to Load the IpAdress , and sometimes it return it instantly !

ps : I checked My Internet connection it works perfectly and i don't think its a connection speed problem !

Thank you !

Answer

With this piece of code it's going to be fast

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