Reputation: 2299
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
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
Reputation: 6268
Following line of code has helped me:
string ip = System.Web.HttpContext.Current.Request.UserHostAddress;
Upvotes: 2
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
Reputation: 4918
try:
HttpContext.Request.UserHostAddress
http://msdn.microsoft.com/en-us/library/system.web.httprequest.userhostaddress%28v=vs.110%29.aspx
Upvotes: 4