Best way to determine if a domain name would be a valid in a “hosts” file?

若如初见. 提交于 2019-12-18 03:58:17

问题


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.


回答1:


How about the System.Uri.CheckHostName() method?

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

Why do the work yourself?




回答2:


These methods are not reliable as you get some response even if the domain name is fake like "fasdfasdfasd.com".

The best way is to send a WebResponse and wait for the response from the domain. Here is the complete code and explanations of this process (long code snippet so not copy-pasting here).

http://www.dotnetfunda.com/articles/show/1072/validating-domain-name-in-aspnet

Thanks



来源:https://stackoverflow.com/questions/967516/best-way-to-determine-if-a-domain-name-would-be-a-valid-in-a-hosts-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!