In this article I will explain with an example, how to get Client IP Address of Visitor’s Machine in ASP.Net MVC.
This article will explain, how to get IP Address of Visitors (Client) Machines which don’t use Proxy Servers and also which are behind Proxy Servers.
Controller
The Controller consists of following Action method.
Action method for handling GET operation
Inside the Action method, first the IP Address is determined using Request.ServerVariables collection for the Client machine’s which are behind Routers or Proxy Servers and hence, the HTTP_X_FORWARDED_FOR server variable is checked.
Note: When the Client machine is behind a Proxy Server its IP Address of the Proxy Server is appended to the Client machine’s IP Address.
If there are multiple Proxy Servers then the IP Addresses of all the Proxy Servers are appended to the client machine IP Address.
If the IP Address is not found in the HTTP_X_FORWARDED_FOR server variable, it means that, it is not using any Proxy Server and hence, the IP Address is now checked in the REMOTE_ADDR server variable.
Note: While running this application on your machine locally i.e. in Visual Studio, the IP Address will show as
127.0.0.1 or
::1.
This happens because in such case the Client and Server both are the same machine.
Thus, no need to worry when you deploy it on a Server, you will see the results.
Finally, the detected IP Address is set into a
ViewBag object and the View is returned.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
string ipAddress = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(ipAddress))
{
ipAddress = Request.ServerVariables["REMOTE_ADDR"];
}
ViewBag.IPAddress = ipAddress;
return View();
}
}
View
HTML Markup
Inside the View, the IP Address is displayed using
ViewBag object.
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<h1>Your IP Address: @ViewBag.IPAddress</h1>
</body>
</html>
Screenshot
Demo
Downloads