ASP. NET Get client IP method
- 2021-09-12 00:52:41
- OfStack
Without saying much, please look at the code:
string requestClientIpAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(requestClientIpAddress))
requestClientIpAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
if (string.IsNullOrEmpty(requestClientIpAddress))
requestClientIpAddress = HttpContext.Current.Request.UserHostAddress;
When tested for load balancing, HttpContext. Current. Request. ServerVariables ["HTTP_X_FORWARDED_FOR"] fetches the real client IP address, while HttpContext. Current. Request. ServerVariables ["REMOTE_ADDR"] and HttpContext. Current. Request. UserHostAddress fetches the assigned reserved address