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

WBOY
Release: 2023-09-19 12:33:02
forward
1374 people have browsed it

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;
      }
   }
}
Copy after login

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;
      }
   }
}
Copy after login

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;
      }
   }
}
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template