Get just the domain name from a URL?

Viewed 80159

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?

13 Answers

Yes, it is possible use:

Uri.GetLeftPart( UriPartial.Authority )

@Dewfy: flaw is that your method returns "uk" for "www.test.co.uk" but the domain here is clearly "test.co.uk".

@naivists: flaw is that your method returns "beta.microsoft.com" for "www.beta.microsoft.com" but the domain here is clearly "microsoft.com"

I needed the same, so I wrote a class that you can copy and paste into your solution. It uses a hard coded string array of tld's. http://pastebin.com/raw.php?i=VY3DCNhp

Console.WriteLine(GetDomain.GetDomainFromUrl("http://www.beta.microsoft.com/path/page.htm"));

outputs microsoft.com

and

Console.WriteLine(GetDomain.GetDomainFromUrl("http://www.beta.microsoft.co.uk/path/page.htm"));

outputs microsoft.co.uk

google.com is not guaranteed to be the same as www.google.com (well, for this example it technically is, but may be otherwise).

maybe what you need is actually remove the "top level" domain and the "www" subodmain? Then just split('.') and take the part before the last part!

Use Nager.PublicSuffix

install-package Nager.PublicSuffix

var domainParser = new DomainParser(new WebTldRuleProvider());

var domainName = domainParser.Get("sub.test.co.uk");
//domainName.Domain = "test";
//domainName.Hostname = "sub.test.co.uk";
//domainName.RegistrableDomain = "test.co.uk";
//domainName.SubDomain = "sub";
//domainName.TLD = "co.uk";

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.

I came up with the below solution (using Linq) :

    public string MainDomainFromHost(string host)
    {
        string[] parts = host.Split('.');
        if (parts.Length <= 2)
            return host; // host is probably already a main domain
        if (parts[parts.Length - 1].All(char.IsNumber))
            return host; // host is probably an IPV4 address
        if (parts[parts.Length - 1].Length == 2 && parts[parts.Length - 2].Length == 2)
            return string.Join(".", parts.TakeLast(3)); // this is the case for co.uk, co.in, etc...
        return string.Join(".", parts.TakeLast(2)); // all others, take only the last 2
    }

I found a solution for myself and this is not using any TLDs or stuff.

It uses the fact that the so called hostname is in the Host-Part of an Uri always at the second last position. Subdomains are always in front of the name and the TLD is always behind it.

See here:

private static string GetNameFromHost(string host)
{
    if (host.Count(f => f == '.') == 1)
    {
        return host.Split('.')[0];
    }
    else
    {
        var _list = host.Split('.').ToList();
        return _list.ElementAt(_list.Count - 2);
    }
}

Because of the numerous variations in domain names and the non-existence of any real authoritative list of what constitutes a "pure domain name" as you describe, I've just resorted to using Uri.Host in the past. To avoid cases where www.google.com and google.com show up as two different domains, I've often resorted to stripping the www. from all domains that contain it, since it's almost guaranteed (ALMOST) to point to the same site. It's really the only simple way to do it without risking losing some data.

Related