Home  >  Article  >  Backend Development  >  How do we get the client's IP address in ASP.NET MVC C#?

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

WBOY
WBOYforward
2023-09-19 12:33:021406browse

Every machine on the network has a unique identifier. just like writing a letter To send in an email, the computer uses a unique identifier to send the data to a specific computers on the network. Most networks today, including all computers on the network The Internet, which uses the TCP/IP protocol as the standard for how to communicate on the Internet network. In the TCP/IP protocol, a computer's unique identifier is called the 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 get the IP address outside the controller, i.e. in a normal class, we can do this 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

我们如何在 ASP.NET MVC C# 中获取客户端的 IP 地址?

Since we are running the application locally, the IP address of the local host is: :1. The name localhost usually resolves to the IPv4 loopback address 127.0.0.1 and resolves to IPv6 loopback address::1

The above is the detailed content of How do we get the client's IP address in ASP.NET MVC C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete