In this article, you will learn how to get the IPv4 IP address of the local machine in C#. To get the IP Address and hostname of the local machine, first, you need to add the namespace
using System.Net;
To get the local hostname or Local computer name, we need to use the static method Dns.GetHostName()
.
// Retrieve the Name of HOST
string hostName = Dns.GetHostName();
To get the local IP address of a local machine, we need to use the static method Dns.GetHostAdresses().
// Get the Local IP Address
string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();
Here is the source code of the program to get the Host Name and the IP address of the Local Machine.
using System;
using System.Net;
namespace Tutorialsrack
{
class Program
{
/* How to Get Local IP Address of the Computer in C# */
static void Main(string[] args)
{
// Retrieve the Name of HOST
string hostName = Dns.GetHostName();
Console.WriteLine("Host Name is(Your Computer Name): {0}",hostName);
// Get the Local IP Address
string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();
Console.WriteLine("Local IP Address is: " + myIP);
//Hit ENTER to exit the program
Console.ReadKey();
}
}
}
I hope this article will help you to understand how to get the IP address of the local machine(Your Computer) in c#
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments