Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
471 views
in Technique[技术] by (71.8m points)

c# - Best way to determine if a domain name would be a valid in a "hosts" file?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

Why do the work yourself?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...