C# program to Display Hostname and IP address


To find the hostname, use the Dns.GetHostName() method in C# −

String hostName = string.Empty;
hostName = Dns.GetHostName();
Console.WriteLine("Hostname: "+hostName);

Now, use the IPHostEntry.AddressList Property to get IP Address −

IPHostEntry myIP = Dns.GetHostEntry(hostName);
IPAddress[] address = myIP.AddressList;

Example

Try the following code to display hostname and IP address −

using System;
using System.Net;
class Program {
   static void Main() {
      String hostName = string.Empty;
      hostName = Dns.GetHostName();
      Console.WriteLine("Hostname: "+hostName);
      IPHostEntry myIP = Dns.GetHostEntry(hostName);
      IPAddress[] address = myIP.AddressList;
      for (int i = 0; i < address.Length; i++) {
         Console.WriteLine("IP Address {1} : ",address[i].ToString());
      }
      Console.ReadLine();
   }
}

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 19-Jun-2020

963 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements