C# : Get Public IP Address

Posting this code snippet, so I don’t forget it!

public static string GetPublicIPAddress()
{
    string result = string.Empty;
 
    // List of public URLs to be tried in order
    string[] checkIPUrl =
    {
        "https://ipinfo.io/ip",
        "https://api.ipify.org",
        "https://icanhazip.com",
        "https://wtfismyip.com/text"
    };
 
    using (var client = new WebClient())
    {
        client.Headers["User-Agent"] = "Mozilla/4.0 (Compatible; Windows NT 5.1; MSIE 6.0) " +
            "(compatible; MSIE 6.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
 
        foreach (var url in checkIPUrl)
        {
            try
            {
                result = client.DownloadString(url);
            }
            catch
            {
                // Ignore errors
            }
 
            if (!string.IsNullOrEmpty(result))
                break;
        }
    }
 
    return result.Replace("\n", "").Trim();
}

C# Code Snippet: Strip All HTML Tags

A quick code snippet to strip all HTML tags using a regular expression. If you are going to call something like this often, then it might be an idea to set the RegEx.Options to Compiled.

using System.Text.RegularExpressions;

public string StripHTMLTags(string text)

{

return Regex.Replace(text, @””, string.Empty);

}

Note: I’m not suggesting using this for a full blown HTML-Sanitiser. See Jeff Atwood’s post and the subsequent comments. (Thanks Piers!)