-2

I'm using Xamarin Studio to develop to iOS and I need a couple of functions to get the Computer Name from the IP and vice-versa

I've tried this code to get the machine name from IP

string machineName = string.Empty;
try
{
    IPHostEntry hostEntry = Dns.GetHostEntry(ipAdress);

    machineName = hostEntry.HostName;
}
catch (Exception ex)
{
    // Machine not found...
}
return machineName;

But I keep getting the machine IP Address, so it's useless because I input the IP Address and get the IP Address.

I've tried something alike to get the IP Address from the HostName I always get the exception "Unable to resolve hostname HITMAN-DESKTOP" being the HITMAN-DESKTOP my remote machine that is accessible from any point in the network and online during the tests.

Any ideas?

Pedro Cavaleiro
  • 835
  • 7
  • 21
  • 1
    Wouldn't `[System.Net.Dns]::GetHostByAddress(.hostname)` be appropriate for this purpose? – gravity Jul 05 '16 at 19:23
  • That's what he's currently using. – Gaspa79 Jul 05 '16 at 19:26
  • As the marked duplicate points out, _"not every IP address has a name"_. Asking the question again won't change that. If you have a more specific scenario that goes beyond the question that's already been asked and answered, please provide those specific details. Explain why you believe the target computer's name _should_ be retrievable, and provide a good [mcve] that shows clearly why should be and how you are not getting the name in that specific scenario. – Peter Duniho Jul 05 '16 at 20:10

1 Answers1

1

The problem with this approach Pedro is that you're not going to get the Computer name using that function unless the DNS has the computer name set as the hostname, which it may or may not have it (hint: probably not).

Computer name is just a local string. The hostname is a network convention that's tied to the IP and you have to set it manually. Most network admins will set the hostname to be the same as the computer name, but it's not guaranteed. You are getting the IP address because of this. "HITMAN-DESKTOP" is not your hostname (network identifier), is the computer name(local identifier) and it's not in the DNS.

In short, I don't think there's a reliable way to do this with pure .NET unless you are 100% sure that all the hostnames you want to check are equal to the computer names.

Gaspa79
  • 5,488
  • 4
  • 40
  • 63