4

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?

Shikkediel
  • 5,195
  • 16
  • 45
  • 77
user3107343
  • 2,159
  • 6
  • 26
  • 37
  • Possible duplicate of [How can I get the client's IP address in ASP.NET MVC?](http://stackoverflow.com/questions/2577496/how-can-i-get-the-clients-ip-address-in-asp-net-mvc) – SJFJ Oct 25 '16 at 12:18

4 Answers4

12

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;
aledpardo
  • 761
  • 9
  • 19
Vasil Dininski
  • 2,368
  • 1
  • 19
  • 31
4

try:

HttpContext.Request.UserHostAddress

http://msdn.microsoft.com/en-us/library/system.web.httprequest.userhostaddress%28v=vs.110%29.aspx

markpsmith
  • 4,860
  • 2
  • 33
  • 62
2

Following line of code has helped me:

string ip = System.Web.HttpContext.Current.Request.UserHostAddress;
OrionMD
  • 389
  • 1
  • 7
  • 13
BJ Patel
  • 6,148
  • 11
  • 47
  • 81
0

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];`  

}

nadun
  • 21
  • 7
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 09 '22 at 13:29