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.
Use a different service, such as ipify.org with json response. It's faster and requires no parsing.
using Newtonsoft.Json;
using System.Net;
namespace Stackoverflow
{
public static class GetExternalIP
{
class IpAddress
{
public string ip { get; set; }
}
public static string GetExternalIp()
{
WebClient client = new WebClient();
string jsonData = client.DownloadString("https://api.ipify.org/?format=json");
IpAddress results = JsonConvert.DeserializeObject<IpAddress>(jsonData);
string externalIp = results.ip;
return externalIp;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.