views:

150

answers:

2

I have a .net site and couple of domains with wildcard dns pointing to it. I use pseudo subdomain system where i extract subdomain name from url with below code

    public static string GetSubdomain()
{
    string domain = HttpContext.Current.Request.Url.Host;
    if (domain.Substring(0, 4).ToLower() == "www.")  // if www exists in the url such as www.subdomain.acme.com
        domain = domain.Remove(0, 4);
    return domain;
}

Code has some limitations. I can not allow users to create sites like subdomain.subdomain.domain.com but subdomain.domain.com.

Due to differend tlds i use (such as site.net, site.mobi, site.co.uk) i couldn't find a solid way to have subdomains with . in it.

Anyone have a snippet where i can use?

A: 

You can extract all parts of the name with a simple regex

using System.Text.RegularExpressions;    
void MatchRegex()
{
        Regex regex = new Regex(@"(?<subdomain>([^\.]*[\.])*)(?<domain>[^\.]+)[\.](?<tld>[^\.]+)$");
        string input = @"sub1.sub2.ttt.com";

        Match   match = regex.Match(input);
       if( match != null )
       {

          string   subDomain = match.Groups["subdomain"].Value;
          string   domain = match.Groups["domain"].Value;
          string   tld = match.Groups["tld"].Value;
       }
}
Ron Harlev
I think that'll fail on .co.uk and similar domains.
Lazarus
Right. it will fail if the TLD has a "." :(
Ron Harlev
yes it does if domain is .co.uk
nLL
If you don't know how many parts are in the TLD (co.uk vs .com) you need some rules or a list of specific TLDs to eliminate the ambiguity
Ron Harlev
I think. i'll have to follow harlevs advice. thanks
nLL
A: 

I'd be tempted to go simple and use something like:

        string fqdn = "test.mydomain.co.uk";
        string[] validDomains = new string[] { "mydomain.co.uk", "mydomain.com", "mydomain.mobi" };

        char[] matchChars = new char[] { '.' };

        string[] stringSegments = fqdn.Split(matchChars, 2);
        if (validDomains.Contains(stringSegments[1]))
        {
            Console.WriteLine("Domain Valid");
        }
        else
        {
            Console.WriteLine("Domain Invalid");
        }
Lazarus