;

How to Get the IPv4 IP Address of the Local Machine in C#


Tutorialsrack 31/07/2020 C#

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

Add namespace
using System.Net;

To Get the Host Name

To get the local hostname or Local computer name, we need to use the static method Dns.GetHostName().

To Get the Host Name
// Retrieve the Name of HOST 
string hostName = Dns.GetHostName(); 

To Get the Local IP Address

To get the local IP address of a local machine, we need to use the static method Dns.GetHostA­dresses().

To Get the Local IP Address
// 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.

How to Get the IPv4 IP Address of the Local Machine in C#
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!


Related Posts



Comments

Recent Posts
Tags