Saturday, February 18, 2012

How to get IP Address and host name of machine?



DNS (Domain Name Service) class provides some useful methods to retrieve local computer Host Name, IP Address and other useful information. DNS class is static class and contains static methods. DNS class is available in System.Net namespace.

Dns class provides GetHostName method which returns local machine’s host name. Another method named GetHostAddresses returns array of IPAddress which accepts hostname as an input. Let’s have a look on below example which displays host name and IP addresses of local machine.

//returns local host name
string localHostName = Dns.GetHostName();
Console.WriteLine("Host name is: {0} ", localHostName);

//returns an array of IPAddresses
IPAddress[] ipAddresses = Dns.GetHostAddresses(localHostName);

//Displays all addresses
Console.Write("All addresses");
foreach (IPAddress ipAddress in ipAddresses)
{
    Console.WriteLine(ipAddress.ToString());
}
           
//Displays only IPV4 address
Console.Write("Only IPV4 addresses");
foreach (IPAddress ipAddress in ipAddresses.Where(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork))
{
    Console.WriteLine(ipAddress.ToString());
}

//Displays only IPV6 addresses
Console.Write("Only IPV6 addresses");
foreach (IPAddress ipAddress in ipAddresses.Where(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetworkV6))
{
    Console.WriteLine(ipAddress.ToString());
}

Output –
Host name is: Mitesh_Laptop

All addresses
fe80::c597:8d4:1936:994%13
fe80::3cda:3d13:f58d:9689%29
18.118.106.118
2001:0:5ef5:79fd:3cda:3d13:f58d:9689

Only IPV4 addresses
18.118.106.118

Only IPV6 addresses
fe80::c597:8d4:1936:994%13
fe80::3cda:3d13:f58d:9689%29
2001:0:5ef5:79fd:3cda:3d13:f58d:9689

Get IP Addresses based on host name

We can also pass any domain name to GetHostAddresses method of DNS class and retrieve all the IP Addresses of that domain.  Let’s have a look on below code.

string hostName = "www.google.com";
foreach (IPAddress ipAddress in Dns.GetHostAddresses(hostName))
{
    Console.WriteLine(ipAddress.ToString());
}

Output –
74.125.236.82
74.125.236.81
74.125.236.83
74.125.236.84
74.125.236.80

Above code displays all the IP Addresses of www.google.com domain. Similarly we can get IP addresses of different domain like www.microsoft.com , www.amazon.com etc.

Get host name based on IP Address

Based on IP address we can retrieve domain name using GetHostEntry method of DNS class. It requires IP address as an input of valid domain. Let’s see how it works.

string IPAddrs = "209.85.175.191";
IPHostEntry hostEntry = Dns.GetHostEntry(IPAddrs);
Console.WriteLine(hostEntry.HostName);

Ouput –
nx-in-f191.1e100.net


See Also –


No comments:

Post a Comment