Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get client IP address in MVC 4 controller?

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?

like image 904
user3107343 Avatar asked Dec 01 '22 16:12

user3107343


1 Answers

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;
like image 111
Vasil Dininski Avatar answered Dec 25 '22 12:12

Vasil Dininski