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

You have a string representation of a host (such as ), 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)
      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();
Next Post Previous Post
No Comment
Add Comment
comment url