Getting exact domain name from any URL [duplicate]

2019-02-11 12:11发布

This question already has an answer here:

I need to extract the exact domain name from any Url.

For example,

Url : http://www.google.com --> Domain : google.com

Url : http://www.google.co.uk/path1/path2 --> Domain : google.co.uk

How can this is possible in c# ? Is there a complete TLD list or a parser for that task ?

标签: c# dns uri tld
5条回答
等我变得足够好
2楼-- · 2019-02-11 12:34

You can use the Uri Class to access all components of an URI:

var uri = new Uri("http://www.google.co.uk/path1/path2");

var host = uri.Host;

// host == "www.google.co.uk"

However, there is no built-in way to strip the sub-domain "www" off "www.google.co.uk". You need to implement your own logic, e.g.

var parts = host.ToLowerInvariant().Split('.');

if (parts.Length >= 3 &&
    parts[parts.Length - 1] == "uk" &&
    parts[parts.Length - 2] == "co")
{
    var result = parts[parts.Length - 3] + ".co.uk";

    // result == "google.co.uk"
}
查看更多
老娘就宠你
3楼-- · 2019-02-11 12:35

use:

var uri =new Uri(Request.RawUrl); // to get the url from request or replace by your own
var domain = uri.GetLeftPart( UriPartial.Authority );

Input:

Url = http://google.com/?search=true&q=how+to+use+google

Result:

domain = google.com 
查看更多
叼着烟拽天下
4楼-- · 2019-02-11 12:36

Use:

new Uri("http://www.stackoverflow.com/questions/5984361/c-sharp-getting-exact-domain-name-from-any-url?s=45faab89-43eb-41dc-aa5b-8a93f2eaeb74#new-answer").GetLeftPart(UriPartial.Authority).Replace("/www.", "/").Replace("http://", ""));

Input:

http://www.stackoverflow.com/questions/5984361/c-sharp-getting-exact-domain-name-from-any-url?s=45faab89-43eb-41dc-aa5b-8a93f2eaeb74#new-answer

Output:

stackoverflow.com

Also works for the following.

http://www.google.com → google.com

http://www.google.co.uk/path1/path2 → google.co.uk

http://localhost.intranet:88/path1/path2 → localhost.intranet:88

http://www2.google.com → www2.google.com

查看更多
冷血范
5楼-- · 2019-02-11 12:47

Try the System.Uri class.

http://msdn.microsoft.com/en-us/library/system.uri.aspx

new Uri("http://www.google.co.uk/path1/path2").Host

which returns "www.google.co.uk". From there it's string manipulation. :/

查看更多
虎瘦雄心在
6楼-- · 2019-02-11 12:49

Another variant, without dependencies:

string GetDomainPart(string url)
{
    var doubleSlashesIndex = url.IndexOf("://");
    var start = doubleSlashesIndex != -1 ? doubleSlashesIndex + "://".Length : 0;
    var end = url.IndexOf("/", start);
    if (end == -1)
        end = url.Length;

    string trimmed = url.Substring(start, end - start);
    if (trimmed.StartsWith("www."))
        trimmed = trimmed.Substring("www.".Length );
    return trimmed;
}

Examples:

http://www.google.com → google.com

http://www.google.co.uk/path1/path2 → google.co.uk

http://localhost.intranet:88/path1/path2 → localhost.intranet:88

http://www2.google.com → www2.google.com

查看更多
登录 后发表回答