Problem Statement
Need to get the IP address of the given machine name as well as need to get the Machine Name from given IP Address.

Solution
Using DNS class in System.Net you can get this information as follows.

Following method will accept any IP Address and returns the valid Machine Name

private static string GetMachineNameFromIPAddress(string ipAdress)
        {
            string machineName = string.Empty;
            try
            {
                System.Net.IPHostEntry hostEntry = System.Net.Dns.GetHostEntry(ipAdress);

                machineName = hostEntry.HostName;
            }
            catch (Exception ex)
            {
                //log here
            }
            return machineName;
        }

The following method will accept any Machine Name and returns the valid IP Address.

private static string GetIPAddressFromMachineName(string machinename)
        {
            string ipAddress = string.Empty;
            try
            {
                System.Net.IPAddress ip = System.Net.Dns.GetHostEntry(machinename).AddressList.Where(o => o.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork).First();

                ipAddress = ip.ToString();
            }
            catch (Exception ex)
            {
                //log here
            }

            return ipAddress;
        }

 

Points to Consider

  • This DNS class will only work on the internal network. You cannot give any public address on the internet.
  • If you connected to any VPN network and run this application. You will see multiple IP addresses returned.