Get IP Address Using C#

Introduction

An IP address is an integral part of networking. This may be not as important from the C# point of view, but we will start to explore the System.Net namespace from here.

In this, we just find the IP Address of the local device.

Ipaddress Logo

Background

In general, we can find our IP address by CMD command, in other words, ipconfig. If you execute this on your Administrator Command Prompt, then you will get the basic Network details like Host Name, IP Address, and Gateway.

Network details

So, to handle this thing, we have a few classes in the System.Net namespace. In this article, we deal with a few.

Procedure To Get IP Address Using C#

Step 1. Start a new Console project in your Visual Studio.

Step 2. Add a namespace in your project as in the following:

Using System.Net;

Step 3. Before fetching the IP Address, we need to know whose IP Address we really want. It's quite understood that we want our own PC. But that must be specified in my code because computers are dumb.

So, we can fetch the machine Name (or Host Name) by the GetHostName() Method. This is inside the DNS class.

Step 4. We are now ready to get the IP address of the Host.

For this, we need to use the GetHostByName() method followed by the AddressList array (first Index).

And, in GetHostByName's argument, we "hostname".

Then, our code looks like this.

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using System.Net; //Include this namespace  
   
   
namespace IpProto  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {   
            string hostName = Dns.GetHostName(); // Retrive the Name of HOST  
            Console.WriteLine(hostName);  
           // Get the IP  
            string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();  
            Console.WriteLine("My IP Address is :"+myIP);  
            Console.ReadKey();  
        }  
    }  
}

Output

Output

And this is my Local IP, so don't be confused. You will have your own.

Conclusion

This was our first step in the System.Net namespace. In a future article, we will deal with a more complex one. For this, I have enclosed my solution file with it. 


Similar Articles