问题描述
在Windows 可以让你的IP来的。我想创建,决定是否给定的名称将是一个有效的主机的文件域名功能
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.
根据的和什么可行的实验和没有按' T,我想出了这个功能:
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;
}
它还有一个好处,它应该使用Unicode名工作(其中一个基本正则表达式将失败)。
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?
更新:作为建议的的的方法几乎不会是我想要的,但它不允许像试验主机名是Windows允许在一个 hosts文件。我会特例 - 的一部分,但我担心有更多的特殊情况。
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.
推荐答案
怎么样的?
private static bool IsValidDomainName(string name)
{
return Uri.CheckHostName(name) != UriHostNameType.Unknown;
}
为什么做这项工作自己呢?
Why do the work yourself?
这篇关于最好的方法来确定是否一个域名将是一个有效的A"主机"文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!