Saturday, August 24, 2019

Get IP Address Using C# Code

In general, we can find our IP address by CMD command in other words ipconfig . And, 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
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. And 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 AddressList array (first Index). 

And, in GetHostByName's argument we "host name".

Then, our code looks like:
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Text;  
  5. using System.Net; //Include this namespace  
  6.    
  7.    
  8. namespace IpProto  
  9. {  
  10.     class Program  
  11.     {  
  12.         static void Main(string[] args)  
  13.         {   
  14.             string hostName = Dns.GetHostName(); // Retrive the Name of HOST  
  15.             Console.WriteLine(hostName);  
  16.            // Get the IP  
  17.             string myIP = Dns.GetHostByName(hostName).AddressList[0].ToString();  
  18.             Console.WriteLine("My IP Address is :"+myIP);  
  19.             Console.ReadKey();  
  20.         }  
  21.     }  
  22. }    
The output will be:
Output

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

No comments:

Post a Comment

How to register multiple implementations of the same interface in Asp.Net Core?

 Problem: I have services that are derived from the same interface. public interface IService { } public class ServiceA : IService { ...