Top level domain from URL in C#

后端 未结 7 1297
误落风尘
误落风尘 2020-11-29 10:11

I am using C# and ASP.NET for this.

We receive a lot of \"strange\" requests on our IIS 6.0 servers and I want to log and catalog these by domain.

Eg. we get

7条回答
  •  天命终不由人
    2020-11-29 10:57

    There may be some examples where this returns something other than what is desired, but country codes are the only ones that are 2 characters, and they may or may not have a short second level (2 or 3 characters) typically used. Therefore, this will give you what you want in most cases:

    string GetRootDomain(string host)
    {
        string[] domains = host.Split('.');
    
        if (domains.Length >= 3)
        {
            int c = domains.Length;
            // handle international country code TLDs 
            // www.amazon.co.uk => amazon.co.uk
            if (domains[c - 1].Length < 3 && domains[c - 2].Length <= 3)
                return string.Join(".", domains, c - 3, 3);
            else
                return string.Join(".", domains, c - 2, 2);
        }
        else
            return host;
    }
    

提交回复
热议问题