简体   繁体   中英

How to get the domain name from an URL

The goal here is to know if aa given URL is in a given domain.

For example, my domain is : www.google.fr I need to know if this : http://token.google.fr/news/something is in the domain

I have a HashSet of Uri with all URL i need to check and my domain also in a Uri object.

Is there a way to do that by manipulating Uri object ?

i Have tried to compare both Uri.Authority but since we might have a prefix and / or a suffix, Uri.Compare() is not usable.

You could split the Uri.Authority and check the TLD and Domain Name which should always be the last two elements of the split (assuming it's a valid URL)

Example

Uri uri1 = new Uri("http://test.google.ca/test/test.html");
Uri uri2 = new Uri("http://google.ca/test/test.html");

string[] uri1Parts = uri1.Authority.Split(new char[] { '.' });
string[] uri2Parts = uri2.Authority.Split(new char[] { '.' });

//Check the TLD and the domain
if (uri1Parts[uri1Parts.Length - 1] == uri2Parts[uri2Parts.Length - 1] && uri1Parts[uri1Parts.Length - 2] == uri2Parts[uri2Parts.Length - 2])
{
    Console.WriteLine(uri1Parts[uri1Parts.Length - 2] + "." + uri1Parts[uri1Parts.Length - 1]);
}

Edit

If your URIs have ports you'll need to take them into account. Here's a little better version.

public static bool AreSameDomain(Uri uri1, Uri uri2)
{
    string uri1Authority = uri1.Authority;
    string uri2Authority = uri2.Authority;

    //Remove the port if port is specified
    if (uri1Authority.IndexOf(':') >= 0)
    {
        uri1Authority = uri1Authority.Substring(0, uri1Authority.IndexOf(':')); 
    }
    if (uri2Authority.IndexOf(':') >= 0)
    {
        uri2Authority = uri1Authority.Substring(0, uri2Authority.IndexOf(':'));
    }

    string[] uri1Parts = uri1Authority.Split(new char[] { '.' });
    string[] uri2Parts = uri2Authority.Split(new char[] { '.' });

    return (uri1Parts[uri1Parts.Length - 1] == uri2Parts[uri2Parts.Length - 1] //Checks the TLD
        && uri1Parts[uri1Parts.Length - 2] == uri2Parts[uri2Parts.Length - 2]); //Checks the Domain Name
}

I could be totally misunderstanding what you are trying to do, but would this be useful:

Uri u1 = new Uri("http://token.google.fr/news/something");
Uri u2 = new Uri("http://www.google.fr");

string domain1 = u1.Authority.Substring(u1.Authority.IndexOf('.') + 1);
string domain2 = u2.Authority.Substring(u2.Authority.IndexOf('.') + 1);

The just compare the two strings "domain1" and "domain2".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM