Iam using Mvc4, I want to get the users ip address of who are using my site. Based on this link I can get user host address, But i want to get exact user ip address
Asked
Active
Viewed 1.8k times
2 Answers
4
Depending on the place you are.
Controller:
ControllerContext.HttpContext.Request.UserHostAddress;
Razor View:
@Request.UserHostAddress
Model:
Do not use System.Web.HttpContext since it's very hard, if not impossible to unit test. Instead, pass the value in through your controller.
Html Helper:
public static MvcHtmlString Ip(this HtmlHelper html)
{
string html = html.ViewContext.RequestContext.HttpContext.Request.UserHostAddress;
return MvcHtmlString.Create(html);
}
Keep in mind, due to simplicity of the examples, I didn't do any null-checking.

Jani Hyytiäinen
- 5,293
- 36
- 45
-
Iam hosting my site in server, By using this code am getting only that server Ip address. But I want users ip address – coder Apr 29 '14 at 05:16
-
This is no longer true in ASP.NET 5 [Core 1.0 (vnext)] :( – Piotr Kula Jan 22 '15 at 13:31
-
@ppumkin Thanks for the heads up. Also, I must comment my own answer that System.Web.HttpContext is actually easy to test with Microsoft Fakes which ships with VS Premium and up. But I won't be changing my answer since I still think it's relevant to stay away from. Especially with vNext which is severing its ties with System.Web. – Jani Hyytiäinen Jan 25 '15 at 10:05
3
Try using following code
System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];

Neel
- 11,625
- 3
- 43
- 61
-
Hi @Neel I've used above mentioned code but I'm getting empty text... Have you encountered this before? Any help? – Mukesh Kumar Feb 20 '17 at 06:13
-