如何正确比较主机名
我有一些主机名需要比较并判断它们是否代表同一主机,例如:
localhost
127.0.0.1
machineName
在 C# 中执行此操作最可靠的方法是什么?现在我正在这样做:
private bool CompareHosts(string host1, string host2)
{
UriBuilder builder1 = new UriBuilder();
builder1.Host = Dns.GetHostAddresses(host1)[0].ToString();
var uri1 = builder1.Uri;
UriBuilder builder2 = new UriBuilder();
builder2.Host = Dns.GetHostAddresses(host2)[0].ToString();
var uri2 = builder2.Uri;
return Uri.Compare(uri1, uri2, UriComponents.Host,
UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) == 0;
}
我没有包括主机地址数组的错误处理,但我不确定如果它将返回多个地址该怎么办,这是否意味着它们将代表不同的机器?有没有更好的方法来比较它们?我需要检查这些主机是否指的是同一台机器。
I have a few host names that I need to compare and tell if they represent the same host, for example:
localhost
127.0.0.1
machineName
What is the most reliable way to do it in C#? For now I'm doing that like:
private bool CompareHosts(string host1, string host2)
{
UriBuilder builder1 = new UriBuilder();
builder1.Host = Dns.GetHostAddresses(host1)[0].ToString();
var uri1 = builder1.Uri;
UriBuilder builder2 = new UriBuilder();
builder2.Host = Dns.GetHostAddresses(host2)[0].ToString();
var uri2 = builder2.Uri;
return Uri.Compare(uri1, uri2, UriComponents.Host,
UriFormat.Unescaped, StringComparison.OrdinalIgnoreCase) == 0;
}
I've not included error handling for host addresses array, but I'm not sure what to do if it will return more then one address, does it mean that they will represent different machines? Is there any better way to compare them? I need to check that those hosts refer to the same machine.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般答案是否定的,如果您有一台带有 2 个网卡的机器(例如),则无法确定它来自同一台机器,因为它实际上是 2 个不同的网络元素。
但是,您可以处理一些特殊情况,例如您提到的 localhost 与 127.0.0.1。
当您从 DNS 查询中获得多个 IP 时,通常意味着这些计算机不相同,因为此技术通常用于不同计算机之间的负载平衡。
过去有很多黑客技术可以发现2个ip是否是同一台机器,在某些情况下你可以得到机器的内部时间,或者如果它按连续顺序打开端口你也可以使用它。但我强烈建议不要走那条路。不进行此检查可能会更好地实现您的目标(例如,如果您有一个 Web 应用程序,您可以轻松地使用 cookie 来实现此目的)。再次强调,需要更多背景信息来提供帮助。
The general answer is no, if you have a machine with 2 network cards (for example), there is no sure way of knowing that it comes from the same machine, since it is really 2 distinct network elements.
However, you can handle some special cases like the localhost versus 127.0.0.1 you mentioned.
When you get multiple IPs from the DNS query it usually means the machines ARE NOT the same since this technique is commonly used for load balancing between different machines.
In the past there were many hacking techniques to discover if 2 ips are the same machines, in some cases you could get the internal time of the machine or if it opened ports in a consecutive order you could also use that. But I strongly advise not going that way. There is probably a better of achieving your goal without doing this check (e.g. if you have a web application you can easily use cookies for this). Again, need more context to help.