Alex Rivera | Logout

Get just the domain name from a URL?

Asked 2010-01-28T11:42:37.303
43

I am trying to extract just the domain name from a URL string. I almost have it... I am using URI

I have a string.. my first thought was to use Regex but then i decided to use URI class

http://www.google.com/url?sa=t&source=web&ct=res&cd=1&ved=0CAgQFjAA&url=http://www.test.com/&rct=j&q=test&ei=G2phS-HdJJWTjAfckvHJDA&usg=AFQjCNFSEAztaqtkaIvEzxmRm2uOARn1kQ

I need to convert the above to google.com and google without the www

I did the following

Uri test = new Uri(referrer);
log.Info("Domain part : " + test.Host);

Basically this returns www.google.com .... i would like to try and return 2 forms if possible... as mentioned...

google.com and google

Is this possible with URI?

Edit
Report

2 Answers

5

Below is some code that will give just the SLD plus gTLD or ccTLD extension (note the exception below). I do not care about DNS.

The theory is as follows:

  • Anything under 3 tokens stays as is e.g. "localhost", "domain.com", otherwise: The last token must be a gTLD or ccTLD extension.
  • The penultimate token is considered part of the extension if it's length < 3 OR if included in a list of exceptions.
  • Finally the token before that one is considered the SLD. Anything before that is considered a subdomain or a host qualifier, e.g. Www.

As for the code, short & sweet:

private static string GetDomainName(string url)
{
    string domain = new Uri(url).DnsSafeHost.ToLower();
    var tokens = domain.Split('.');
    if (tokens.Length > 2)
    {
        //Add only second level exceptions to the < 3 rule here
        string[] exceptions = { "info", "firm", "name", "com", "biz", "gen", "ltd", "web", "net", "pro", "org" }; 
        var validTokens = 2 + ((tokens[tokens.Length - 2].Length < 3 || exceptions.Contains(tokens[tokens.Length - 2])) ? 1 : 0);
        domain = string.Join(".", tokens, tokens.Length - validTokens, validTokens);
    }
    return domain;
}

The obvious exception is that this will not deal with 2-letter domain names. So if you're lucky enough to own ab.com you'll need to adapt the code slightly. For us mere mortals this code will cover just about every gTLD and ccTLD, minus a few very exotic ones.

answered 2012-11-15T13:46:26.410
3

I think you are displaying a misunderstanding of what constitutes a "domain name" - there is no such thing as a "pure domain name" in common usage - this is something you will need to define if you want consistent results.
Do you just want to strip off the "www" part? And then have another version which strips off the top level domain (eg. strip off the ".com" or the ".co.uk" etc parts?) Another answer mentions split(".") - you will need to use something like this if you want to exclude specific parts of the hostname manually, there's nothing within the .NET framework to meet your requirements exactly - you'll need to implement these things yourself.

answered 2010-01-28T13:08:55.417

Your Answer