Was it helpful?

Question

How can we get the client's IP address in ASP.NET MVC C#?

CsharpServer Side ProgrammingProgramming

Every machine on a network has a unique identifier. Just as you would address a letter to send in the mail, computers use the unique identifier to send data to specific computers on a network. Most networks today, including all computers on the internet, use the TCP/IP protocol as the standard for how to communicate on the network. In the TCP/IP protocol, the unique identifier for a computer is called its IP address.

Using HttpRequest.UserHostAddress property

Example

using System.Web.Mvc;
namespace DemoMvcApplication.Controllers{
   public class HomeController : Controller{
      public string Index(){
         string ipAddress = Request.UserHostAddress;
         return ipAddress;
      }
   }
}

If we want to fetch IP address outside the controller i.e. in a normal class, we can do like below.

using System.Web;
namespace DemoMvcApplication.Helpers{
   public static class DemoHelperClass{
      public static string GetIPAddress(){
         string ipAddress = HttpContext.Current.Request.UserHostAddress;
         return ipAddress;
      }
   }
}

Example using ServerVariables

using System.Web.Mvc;
namespace DemoMvcApplication.Controllers{
   public class HomeController : Controller{
      public string Index(){
         string ipAddress = Request.ServerVariables["REMOTE_ADDR"];
         return ipAddress;
      }
   }
}

Output

Since we are running the application locally, the ip address for the localhost is ::1. The name localhost normally resolves to the IPv4 loopback address 127.0.0.1, and to the IPv6 loopback address ::1

raja
Published on 24-Sep-2020 16:14:49
Advertisements
Was it helpful?
Not affiliated with Tutorialspoint
scroll top