How to get client IP address in MVC 4 controller?

asp.net-mvc-4, c#

Solution

Either of these should work, from inside your `Controller`:

method 1:

string userIpAddress = this.Request.ServerVariables["REMOTE_ADDR"];

method 2:

string userIpAddress = this.Request.UserHostAddress;

Problem

I tried to get client IP adress in controller. It is working but sometimes I get this error: ``` The underlying connection was closed: An unexpected error occurred on a receive String IP = ""; using (WebResponse response = request.GetResponse()) { using (StreamReader stream = new StreamReader(response.GetResponseStream())) { IP = stream.ReadToEnd(); } } int first = IP.IndexOf("Address: ") + 9; int last = IP.LastIndexOf("</body>"); IP = IP.Substring(first, last - first); ``` Is there any different method for getting client IP address?

Original source

Related problems