Skip to content

Instantly share code, notes, and snippets.

@motowilliams
Created March 13, 2014 15:57
Show Gist options
  • Save motowilliams/9531160 to your computer and use it in GitHub Desktop.
Save motowilliams/9531160 to your computer and use it in GitHub Desktop.
Returns the first segment past known TlDs
/// <summary>
/// Returns the first segment past known TLDs
/// </summary>
/// <param name="uri">Source Uri</param>
/// <param name="tlds">http://data.iana.org/TLD/tlds-alpha-by-domain.txt</param>
/// <returns>Target Uri</returns>
private static Uri CleanHostHeaders(Uri uri, IEnumerable<string> tlds)
{
// IANA currently has the list upper case
string host = uri.Host.ToUpper();
var hostSegments = host.Split('.');
var matchedSegments = new List<string>();
for (int i = hostSegments.Length; i >= 1; i--)
{
string segment = hostSegments[i - 1];
if (tlds.Any(x => x.Contains(segment)))
matchedSegments.Add(segment);
else
{
// There wasn't a match so mean it could be the
// domain name if we've found any tld match
if (matchedSegments.Any())
{
matchedSegments.Add(hostSegments[i - 1]);
break;
}
}
}
matchedSegments.Reverse();
return new Uri(string.Concat(uri.Scheme, Uri.SchemeDelimiter, string.Join(".", matchedSegments)));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment