We can easily find the IP address and hostname in the machine using the Windows UI or the ipconfig
command. In this blog, we will see how to get these values programmatically using C#.
We will use Dns (Domain Name Service) class to get the IP address and hostname of the machine. The Dns class is available under the namespace System.Net
that has methods to retrieve IP Addresses, Host Names.
Get Hostname Using C#:
Method 1:
The Dns.GetHostName()
method is used to get the hostname of the machine as shown below,
// Get hostname - Method 1
var hostName = Dns.GetHostName();
// Print host/machine name
Console.WriteLine("Host/Machine Name(Method 1): " + hostName);
Method 2:
We will also use Environment.MachineName
property to get the hostname of the machine.
// Get hostname - Method 2
var hostName1 = Environment.MachineName;
Console.WriteLine("Host/Machine Name(Method 2): " + hostName1);
Get IP Address Using C#:
The Dns.GetHostAddresses()
is used to query the DNS subsystem for the IP addresses associated with a hostname.
// Get IP addresses of the machine
IPAddress[] ipaddress = Dns.GetHostAddresses(hostName);
Console.WriteLine("IP Address: ");
foreach (IPAddress ip in ipaddress)
{
// Print IP address
Console.WriteLine(ip.ToString());
}
Entire Code snippet:
using System;
using System.Net;
namespace GetIpAddressAndHostName
{
class Program
{
static void Main(string[] args)
{
// Get hostname - Method 1
var hostName1 = Dns.GetHostName();
// Print host/machine name
Console.WriteLine("Host/Machine Name(Method 1): " + hostName1);
// Get hostname - Method 2
var hostName2 = Environment.MachineName;
Console.WriteLine("Host/Machine Name(Method 2): " + hostName2);
// Get IP addresses of the machine
IPAddress[] ipaddress = Dns.GetHostAddresses(hostName1);
Console.WriteLine("IP Address: ");
foreach (IPAddress ip in ipaddress)
{
// Print IP address
Console.WriteLine(ip.ToString());
}
Console.ReadKey();
}
}
}
Output:
Host/Machine Name(Method 1): LAPTOP-153AEC234
Host/Machine Name(Method 2): LAPTOP-153AEC234
IP Address:
fa90::e6c1:5681:f12d:3214%95
162.18.45.2
192.168.2.4
Get the IPAddress of a Domain Name:
The Dns.GetHostAddresses()
is used to get the IP addresses of the domain as shown below,
using System;
using System.Net;
namespace GetIpAddressDomain
{
class Program
{
static void Main(string[] args)
{
string domainName = "www.google.com";
// Get IP address of the domain
IPAddress[] ipaddressArray = Dns.GetHostAddresses(domainName);
Console.WriteLine(domainName + "'s IP address: ");
foreach (IPAddress ipaddress in ipaddressArray)
{
// Print IP address
Console.WriteLine(ipaddress);
}
Console.ReadKey();
}
}
}
Output:
www.google.com's IP address:
172.217.24.36
Comments (0)