user3107343 user3107343 - 2 months ago 20x
C# Question

How to get client IP adress in MVC 4 controller?

I tried get client IP adress in controller.It is working but some times 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 a different method for get client IP address.


Either of these should work:

method 1:

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

method 2:

string userIpAddress = this.Request.UserHostAddres;