Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve hostname from local IP in C#.NET?

Tags:

c#

.net

I'm trying to list the names of the computer names currently online on a network. I've only managed to get the get active IPs but I cannot get the computer name of these IPs. Any ideas ?

like image 390
Ahmed Mohamed Avatar asked Jun 20 '12 16:06

Ahmed Mohamed


People also ask

How do I resolve an IP address to a hostname?

Querying DNS Click the Windows Start button, then "All Programs" and "Accessories." Right-click on "Command Prompt" and choose "Run as Administrator." Type "nslookup %ipaddress%" in the black box that appears on the screen, substituting %ipaddress% with the IP address for which you want to find the hostname.

How do I find my host C IP address?

Here is a simple method to find hostname and IP address using C program. gethostname() : The gethostname function retrieves the standard host name for the local computer. gethostbyname() : The gethostbyname function retrieves host information corresponding to a host name from a host database.


2 Answers

You can use Dns.GetHostEntry to try to resolve the name, because not every IP has a name.

using System.Net;
...

public string GetHostName(string ipAddress)
{
    try
    {
        IPHostEntry entry = Dns.GetHostEntry(ipAddress);
        if (entry != null)
        {
           return entry.HostName;
        }
    }
    catch (SocketException ex)
    {
       //unknown host or
       //not every IP has a name
       //log exception (manage it)
    }

    return null;
}
like image 172
Daniel Peñalba Avatar answered Oct 08 '22 20:10

Daniel Peñalba


If you've already got a list of ip adresses, you can find the name with:

      System.Net.Dns.GetHostEntry("youripaddress").HostName;
like image 37
Me.Name Avatar answered Oct 08 '22 18:10

Me.Name