Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get just the domain name from a URL?

Tags:

c#

uri

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?

like image 421
mark smith Avatar asked Jan 28 '10 11:01

mark smith


People also ask

What is parse domain?

Splits a hostname into subdomains, domain and (effective) top-level domains. Since domain name registrars organize their namespaces in different ways, it's not straight-forward to split a hostname into subdomains, the domain and top-level domains.

How do I find a domain name from an IP address?

You can use nslookup on the IP. Reverse DNS is defined with the . in-addr.arpa domain. this will ask 3.2.21.123.in-addr.arpa and yield the domain name (if there is one defined for reverse DNS).

Are domain name and URL the same thing?

While the domain is the name of the website, a URL will lead to any one of the pages within the website. Every URL contains a domain name, as well as other components needed to locate the specific page or piece of content.


2 Answers

Yes, it is possible use:

Uri.GetLeftPart( UriPartial.Authority ) 
like image 78
Dewfy Avatar answered Oct 02 '22 23:10

Dewfy


@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

like image 34
servermanfail Avatar answered Oct 02 '22 23:10

servermanfail