Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get user IP address in mvc [duplicate]

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

like image 436
coder Avatar asked Apr 28 '14 07:04

coder


2 Answers

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.

like image 154
Jani Hyytiäinen Avatar answered Oct 02 '22 19:10

Jani Hyytiäinen


Try using following code

 System.Web.HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
like image 28
Neel Avatar answered Oct 02 '22 19:10

Neel