How to properly compare host names

I have several host names that I need to compare and say if they represent the same host, for example:

localhost 127.0.0.1 machineName 

What is the most reliable way to do this in C #? So far I am doing this as:

  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 did not enable error handling for the host address array, but I'm not sure what to do if it returns more than one address, does this mean that they will represent different machines? Is there a better way to compare them? I need to verify that these hosts refer to the same computer.

+6
source share
1 answer

General answer: no, if you have a machine with two network cards (for example), there is no sure way to find out that it comes from the same computer, since these are really two different network elements.

However, you can handle some special cases, such as localhost versus 127.0.0.1, which you mentioned.

When you get multiple IP addresses from a DNS query, this usually means that the machines DO NOT match, since this method is usually used to balance the load between different machines.

There were many hacking methods in the past to detect if 2 ips are the same machines, in some cases you can get the internal time of the machine or open the ports in serial order, you can also use this. But I strongly advise you not to go this route. It is probably best to achieve your goal without performing this check (for example, if you have a web application, you can easily use cookies for this). Again, more context is needed to help.

+2
source

Source: https://habr.com/ru/post/901608/


All Articles