Home > other >  ASP.NET MVC gets client IP from different range than IP detection sites
ASP.NET MVC gets client IP from different range than IP detection sites

Time:12-29

If I go to https://whatismyipaddress.com/ or similar, I get an IP address from the 194.11x.x.x range.

If I go to my ASP.NET MVC application from the same computer, it uses context.Connection.RemoteIpAddress in the middleware, and it gets a 10.x.x.x range. I land in the same range if I access my web site from my mobile, which is in the mobile network.

What happens here? I mean it should be some router or something, but why do IP detection sites get my IP right, but my ASP.NET host not?

CodePudding user response:

It is because you're trying to get the IP from your local machine. If you deploy the application it should display your IP instead of your local IP.

CodePudding user response:

For the reference, in case somebody stumbles upon this. On most websites you get code like context.Connection.RemoteIpAddress to get the client IP, including this middleware guide: https://docs.microsoft.com/en-us/aspnet/core/security/ip-safelist?view=aspnetcore-6.0

Everything works until you deploy to a hosting with reverse proxy (thank you @Llama), where in order to prevent DDoS attacks your request lands on a proxy that forwards your request to your website.

Most hostings would pass the original IP along though. You can get it like context.Request.Headers["X-Forwarded-For"].FirstOrDefault().

  • Related