I have an asp.net website in which I am getting the external IP using the below code.
public static string GetExternalIp()
{
try
{
string externalIP = "";
externalIP = (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;
return Dns.GetHostByName(Environment.MachineName).AddressList[0].ToString();
}
}
The code is getting the external IP perfectly however, it takes 3 to 5 secs to get the public IP to my application. Based on this stackoverflow post Public IP Address i added the below line to my code as the user has mentioned this will be faster for the consecutive times in getting the public IP
public static WebClient webclient = new WebClient();
However this is also taking time. I googled and found another code using HTTPWebRequest. Below is the code
string myExternalIP;
string strHostName = System.Net.Dns.GetHostName();
string clientIPAddress = System.Net.Dns.GetHostAddresses(strHostName).GetValue(0).ToString();
string clientip = clientIPAddress.ToString();
System.Net.HttpWebRequest request =
(System.Net.HttpWebRequest) System.Net.HttpWebRequest.Create("http://www.whatismyip.org");
request.UserAgent = "User-Agent: Mozilla/4.0 (compatible; MSIE" +
"6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
System.Net.HttpWebResponse response =
(System.Net.HttpWebResponse) request.GetResponse();
using(System.IO.StreamReader reader = new StreamReader(response.GetResponseStream())) {
myExternalIP = reader.ReadToEnd();
reader.Close();
}
This code is fast but its creating a html document containing the public IP.
How to get only the IP address from that HTML document?
Is there any code which will be more fast than the one I am currently using.