Convert Host Name to IP Address or Find IP address of a host -C#

You have a string representation of a host (such as www.google.com ), and you need to obtain the IP address from this hostname.

using System;
using System.Collections.Generic;
using System.Text;
using System.Net;

namespace ConsoleApplication1
{
  class Program
  {
      static void Main(string[] args)
      {
          Console.WriteLine(HostName2IP("www.google.com"));
          Console.Read();
      }
      public static string HostName2IP(string hostname)
      {
          // Resolve the hostname into an iphost entry using the Dns class.
          IPHostEntry iphost = System.Net.Dns.GetHostEntry(hostname);
          // Get all of the possible IP addresses for this hostname.
          IPAddress[] addresses = iphost.AddressList;
          // Make a text representation of the list.

          StringBuilder addressList = new StringBuilder();
          // Get each IP address.
          foreach (IPAddress address in addresses)
          {
              // Append it to the list.
              addressList.AppendFormat("IP Address: {0};", address.ToString());
          }
          return addressList.ToString();
      }
  }
}

Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post