Home > Article > Backend Development > How do we get the client's IP address in ASP.NET MVC C#?
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 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; } } }
using System.Web.Mvc; namespace DemoMvcApplication.Controllers{ public class HomeController : Controller{ public string Index(){ string ipAddress = Request.ServerVariables["REMOTE_ADDR"]; return ipAddress; } } }
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!