views:

279

answers:

2

The Windows Hosts file allows you to associate an IP to a host name that has far greater freedom than a normal Internet domain name. I'd like to create a function that determines if a given name would be a valid "host" file domain name.

Based on this answer and experimentation of what works and doesn't, I came up with this function:

private static bool IsValidDomainName(string domain)
{
    if (String.IsNullOrEmpty(domain) || domain.Length > 255)
    {
     return false;
    }

    Uri uri;

    if (!Uri.TryCreate("http://" + domain, UriKind.Absolute, out uri))
    {
     return false;
    }

    if (!String.Equals(uri.Host, domain, StringComparison.OrdinalIgnoreCase) || !uri.IsWellFormedOriginalString())
    {
     return false;
    }

    foreach (string part in uri.Host.Split('.'))
    {
     if (part.Length > 63)
     {
      return false;
     }
    }

    return true;
}

It also has the benefit that it should work with Unicode names (where a basic regex would fail).

Is there a better/more elegant way to do this?

UPDATE: As suggested by Bill, the Uri.CheckHostName method almost does what I want, but it doesn't allow for host names like "-test" that Windows allows in a "hosts" file. I would special case the "-" part, but I'm concerned there are more special cases.

+2  A: 

How about:

 private static bool IsValidDomainName(string name)
 {
  return Uri.CheckHostName(name) != UriHostNameType.Unknown;
 }

Why do the work yourself?

Bill
Note that even passing null or empty string returns the correct answer.
Bill
I hadn't seen this method before. I missed it in my Reflector-ing. It's better than my "http" prefix hack, but the hosts file allows "-test" for a name, but this function says it's invalid.
Jeff Moser
The "http" prefix hack correctly allows the "-test" case, but just using Uri.CheckHostName does not allow it.
Jeff Moser
I am not aware of all that is allowed in the hosts file, for example, "-test".
Bill
A: 

Some problems I found with this method:

  • Allows some punctuation (at least the underscore) that's disallowed in DNS.
  • Allows domain names that begin and end with a hyphen.
  • Allows invalid TLDs.

There may be more.

Here's one reference - more are easy to find.

Are you adding non-existent names to a host file? If you're adding hostnames that actually exist, a DNS lookup is probably the easiest thing.

Michael Petrotta
Yeah, these are all names that don't exist in DNS. Note that "hosts" allows much more things than what the register.com link you gave allows.
Jeff Moser