The client IP address returns the same internal network address

I am trying to get the IP address of a user from ASP.NET MVC 5. I was looking for various examples, such as:

All of them gave the same result: the user is considered internal on the network. I had friends who tried their phones (which are not online). Here is my last attempt:

private static Logger _logger = LogManager.GetCurrentClassLogger(); public static bool IsIpInternal() { var ipAddress = HttpContext.Current.Request.UserHostAddress; var logEvent = new LogEventInfo(LogLevel.Info, _logger.Name, ipAddress); _logger.Log(logEvent); try { if (ipAddress != null) { var ipParts = ipAddress.Split(new[] { "." }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse).ToArray(); var isDebug = System.Diagnostics.Debugger.IsAttached; if (ipParts[0] == 10) { return true; } } } catch (Exception e) { logEvent = new LogEventInfo(LogLevel.Error, _logger.Name, e.Message); _logger.Log(logEvent); return false; } return false; } 

The log displays 10.xxx.xx.xxx for all requests (based on the log). This is the internal address, not the IP address of the client connecting to the web application. IsIpInternal() always returns true. What am I doing wrong?

Please note that I ignore the addresses 192.168.xx and 172.16.xxx.xxx as internal.

+5
source share
1 answer

If your website is behind a load balancer, a common problem is the appearance of a load balancer IP address when you expect a client IP address. This is because the load balancer is actually the only client that the web application knows with.

There are two ways to handle this:

  • You can configure the load balancer to add an additional HTTP header ( x-forwarded-for ), which indicates the source IP address. You will need to change your website to look at this header instead of UserHostAddress, for example:

     //var clientIP = HttpContext.Current.Request.UserHostAddress; var clientIP = HttpContext.Current.Request.Headers["x-forwarded-for"]; 

    Note: the x-forwarded-for header can actually return a comma-delimited list of IP addresses in some cases. To be compatible with this case, you can write this instead:

     var clientIP = HttpContext.Current.Request.Headers["x-forwarded-for"].Split(',')[0]; 
  • You can configure specific LBs to transmit over the client IP address by copying the IP header packet. For Citrix Netscaler, see this article for more information.

+6
source

Source: https://habr.com/ru/post/1269684/


All Articles