Get IP Address and Host Name With C# 10

In this article, we will show you how to get the IP address and host name with C# 10. We will be using the System.Net.Dns class for this purpose.

The DNS class provides a set of methods that allow you to perform DNS operations such as querying DNS servers for resource records, resolving domain names into IP addresses, and more. Let’s get started!

To get started, we need to create a C# console application. You can do this in Visual Studio by going to File->New Project->Visual C#->Console Application. Name your project “getIP”.

Once the project has been created, open the Program.cs file and add the following code:


Copy-paste the code below and run it.

using System.Net.Sockets;
using System.Net;
using System.Net.NetworkInformation;
var getip = getIP();
Console.WriteLine("Your IP Address is :" + getip );
String hostName = Dns.GetHostName();
Console.WriteLine("Computer name :" + hostName);

static string getIP()
    var myhost = Dns.GetHostEntry(Dns.GetHostName());
    foreach (var ipaddr in myhost.AddressList)
        if (ipaddr.AddressFamily == AddressFamily.InterNetwork)
            return ipaddr.ToString();
    throw new Exception("No network adapters with an IPv4 address was found");

To run the code, run dotnet run and you should see your IP and hostname is the following format.

Your IP Address is :
Computer name :PC-01