TechieClues TechieClues
Updated date Jul 16, 2023
In this blog, we will learn how to retrieve the IP address and hostname of a device using C#. This complete guide explores three methods - utilizing the Dns class, NetworkInterface class, and WMI (Windows Management Instrumentation).
  • 9.7k
  • 0
  • 0

Introduction:

In today's interconnected world, knowing how to retrieve the IP address and hostname of a device can be incredibly useful. Whether you're building network monitoring tools, debugging applications, or implementing security measures, having access to this information is crucial. In this blog, we will explore various methods to obtain the IP address and hostname using C#, providing detailed explanations and code examples along the way.

Get Hostname Using C#:

Method 1: Using the Dns Class:

The Dns class in C# provides a straightforward way to retrieve information related to domain names, IP addresses, and host names. The Dns.GetHostName() method is used to get the hostname of the machine. By utilizing the Dns.GetHostEntry() or Dns.GetHostAddresses() method, we can obtain the IP address and hostname of a given device. Here's an example program:

// Get hostname - Method 1
var hostName = Dns.GetHostName();
// Print host/machine name
Console.WriteLine("Host/Machine Name(Method 1): " + hostName);

Using Environment.MachineName

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:5881:f12d:3214%95
162.180.45.2
192.168.28.4

Get the IP address 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

Method 2: Utilizing NetworkInterface Class:

Another way to obtain IP address and hostname information is by using the NetworkInterface class from the System.Net.NetworkInformation namespace. This method allows access to detailed network interface information. Here's an example program:

using System;
using System.Net;
using System.Net.NetworkInformation;

class Program
{
    static void Main()
    {
        string hostName = Dns.GetHostName();
        Console.WriteLine($"Host Name: {hostName}");

        NetworkInterface[] networkInterfaces = NetworkInterface.GetAllNetworkInterfaces();
        foreach (NetworkInterface networkInterface in networkInterfaces)
        {
            IPInterfaceProperties properties = networkInterface.GetIPProperties();
            foreach (IPAddressInformation address in properties.UnicastAddresses)
            {
                Console.WriteLine($"IP Address: {address.Address}");
            }
        }
    }
}

Output:

Host Name: LAPTOP-153AEC234
IP Address: fa90::e6c1:5881:f12d:3214%95
162.180.45.2
192.168.28.4

Method 3: Using WMI (Windows Management Instrumentation):

The Windows Management Instrumentation (WMI) provides a powerful way to access and manage various system-related information, including IP addresses and host names. We can use the ManagementObjectSearcher class to query the WMI and retrieve the desired data. Here's an example program:

using System;
using System.Management;

class Program
{
    static void Main()
    {
        string query = "SELECT * FROM Win32_NetworkAdapterConfiguration WHERE IPEnabled = 'TRUE'";
        ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
        ManagementObjectCollection collection = searcher.Get();

        foreach (ManagementObject obj in collection)
        {
            string hostName = obj["DNSHostName"] as string;
            Console.WriteLine($"Host Name: {hostName}");

            string[] ipAddresses = obj["IPAddress"] as string[];
            foreach (string ipAddress in ipAddresses)
            {
                Console.WriteLine($"IP Address: {ipAddress}");
            }
        }
    }
}

Output:

Host Name: LAPTOP-153AEC234
IP Address: fa90::e6c1:5881:f12d:3214%95
162.180.45.2
192.168.28.4

All three methods discussed in this blog have their own advantages and use cases. The first method using the Dns class is the simplest and most straightforward, suitable for most scenarios. The second method using the NetworkInterface class provides more extensive network information. Finally, the third method using WMI offers greater flexibility but requires more advanced knowledge.

Conclusion:

In this blog, we explored three different methods to obtain the IP address and hostname using C#. We discussed the usage of the Dns class, the NetworkInterface class, and the Windows Management Instrumentation (WMI). 

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!