using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Net; using Yaulw.Registry; namespace TCMPortMapper.Helpers { public static class Utility { /// /// This function uses a Web request to find the external IP Address your machine is using /// /// Number of miliseconds to wait for a response /// Tells if we should attempt to get the external ip in multiple tries /// External facing IP address public static string GetExternalIP(int pTimeOutMiliSeconds, bool forceMultipleChecks) { var externalIP = Yaulw.Net.IPHostHelper.GetExternalIP(forceMultipleChecks); if (externalIP == null || externalIP == IPAddress.None) return string.Empty; return externalIP.ToString(); } /// /// This function uses a Web request to find the external IP Address your machine is using /// /// Number of miliseconds to wait for a response /// External facing IP address public static string GetExternalIP(int pTimeOutMiliSeconds) { string whatIsMyIp = "http://automation.whatismyip.com/n09230945.asp"; WebClient wc = new WebClient(); UTF8Encoding utf8 = new UTF8Encoding(); try { string ipaddr = null; bool done = false; wc.DownloadDataCompleted += new DownloadDataCompletedEventHandler((object sender, DownloadDataCompletedEventArgs e) => { ipaddr = utf8.GetString(e.Result); done = true; }); wc.DownloadDataAsync(new Uri(whatIsMyIp)); System.DateTime startTime = System.DateTime.Now; while (!done) { System.TimeSpan sp = System.DateTime.Now - startTime; // We should get a response in less than timeout. // If not, we cancel all and return the internal IP Address if (sp.TotalMilliseconds > pTimeOutMiliSeconds) { done = true; wc.CancelAsync(); } } return ipaddr; } catch { return null; } finally { if (wc != null) { wc.Dispose(); wc = null; } } } } }