Exemplo n.º 1
0
        /// <summary>
        /// Performs an automated lookup at whatismyip.com to determine the external IP of the calling server
        /// </summary>
        /// <returns>A string with the external IP of the calling server</returns>
        public static string WhatIsMyIP()
        {
            // LOOK FOR CACHED IP INFORMATION
            Cache cache = HttpContextHelper.SafeGetCache();

            if (cache != null && cache["WhatIsMyIP"] != null)
            {
                return((string)cache["WhatIsMyIP"]);
            }

            // TRY TO GET IP FROM WEBSERVICE
            string response = string.Empty;

            try
            {
                HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create("http://www.whatismyip.com/automation/n09230945.asp");
                httpWebRequest.Method = "GET";
                using (StreamReader responseStream = new StreamReader(httpWebRequest.GetResponse().GetResponseStream(), System.Text.Encoding.UTF8))
                {
                    response = responseStream.ReadToEnd();
                    responseStream.Close();
                }
                if (!Regex.IsMatch(response, @"^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$"))
                {
                    response = string.Empty;
                }
            }
            catch { }

            // CACHE AND RETURN RESPONSE
            if (cache != null)
            {
                cache.Add("WhatIsMyIP", response, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, 10, 0), CacheItemPriority.Normal, null);
            }
            return(response);
        }