Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
C# program to Display Hostname and IP address
To find the hostname of the current machine, use the Dns.GetHostName() method in C#. This method returns the host name of the local computer as a string. To get the IP addresses, use the IPHostEntry.AddressList property which provides an array of all IP addresses associated with the hostname.
Syntax
Following is the syntax for getting the hostname −
string hostName = Dns.GetHostName();
Following is the syntax for getting IP addresses −
IPHostEntry hostEntry = Dns.GetHostEntry(hostName); IPAddress[] addresses = hostEntry.AddressList;
Example
The following code demonstrates how to display hostname and IP addresses −
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 {0}: {1}", i + 1, address[i].ToString());
}
}
}
The output of the above code is −
Hostname: DESKTOP-ABC123 IP Address 1: 192.168.1.100 IP Address 2: ::1 IP Address 3: 127.0.0.1
Using GetHostEntry with Different Parameters
You can also get host information using an IP address or a specific hostname −
using System;
using System.Net;
class Program {
static void Main() {
try {
// Get host info by IP address
IPHostEntry hostInfo = Dns.GetHostEntry("127.0.0.1");
Console.WriteLine("Host name for 127.0.0.1: " + hostInfo.HostName);
// Get host info by domain name
IPHostEntry googleInfo = Dns.GetHostEntry("google.com");
Console.WriteLine("IP addresses for google.com:");
foreach (IPAddress ip in googleInfo.AddressList) {
Console.WriteLine(ip.ToString());
}
} catch (Exception ex) {
Console.WriteLine("Error: " + ex.Message);
}
}
}
The output of the above code is −
Host name for 127.0.0.1: localhost IP addresses for google.com: 142.250.191.46 2607:f8b0:4004:c1b::65 2607:f8b0:4004:c1b::71 2607:f8b0:4004:c1b::8a 2607:f8b0:4004:c1b::66
Key Points
-
Dns.GetHostName()returns the hostname of the local machine. -
Dns.GetHostEntry()can accept a hostname or IP address as parameter. -
The
AddressListproperty contains both IPv4 and IPv6 addresses. -
Always use try-catch blocks when working with DNS operations as they can throw exceptions.
Conclusion
The Dns class in C# provides methods to retrieve hostname and IP address information. Use GetHostName() for the local machine's hostname and GetHostEntry() to resolve hostnames to IP addresses or vice versa.
