user3107343
user3107343

Reputation: 2299

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?

Upvotes: 4

Views: 30308

Answers (4)

nadun
nadun

Reputation: 29

System.Web.HttpContext.Current.Request.UserHostAddress this gives user host address and it's not real request IP.

Request.ServerVariables["REMOTE_ADDR"] also returns the same.

Because if the request has been passed on by one, or more, proxy servers then the IP address returned by HttpRequest.UserHostAddress property will be the IP address of the last proxy server that relayed the request.

You can use this string manipulation to get the correct Ip of the request

string ipAddressInfo = request.ServerVariables["HTTP_X_FORWARDED_FOR"]; 
   
if (ipAddressInfo.Split(',') > 0){
  `string clientIpAddress = ipAddressInfo.Split(',')[0];`  

}

Upvotes: 0

BJ Patel
BJ Patel

Reputation: 6268

Following line of code has helped me:

string ip = System.Web.HttpContext.Current.Request.UserHostAddress;

Upvotes: 2

Vasil Dininski
Vasil Dininski

Reputation: 2418

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;

Upvotes: 12

Related Questions