Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to correctly compare host names

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.

like image 637
username Avatar asked Nov 16 '11 12:11

username


1 Answers

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.

like image 50
idanzalz Avatar answered Oct 10 '22 09:10

idanzalz