Search code examples
c#asp.net.net.net-coreipv6

`(AuthenticationHandler.)Context.Connection.RemoteIPAddress` returns `::ffff:192.168.1.12` on Windows


What I Do

I am issuing a HTTP request from a remote client on the same IPv4 local network as a .NET Core ASP server. This server is configured to authenticate requests with a subclass of AuthenticationHandler that accesses the remote IP address through Context.Connection.RemoteIPAddress.

What I Expect

When the application is running on a Unixy system, Context.Connection.RemoteIPAddress returns an IPAddress that is represented as the expected "192.168.1.12".

What Happens

When the application is running on a Windows system, Context.Connection.RemoteIPAddress returns an IPAddress that is represented as "::ffff:192.168.1.12".

Problem

I want to compare the return value of RemoteIPAddress to another IPAddress value, that, however, is represented as the plain "192.168.1.12". Thus, the two addresses compare as unequal, even though they are (or should be!) the same.

Non-Solutions

This is an IPv4-only network, so there's been no point in trying to block IPv6 traffic.

I also don't want to do some sort of fuzzy string comparison; even though it would work and I can't see any problem with it, I have a sense there's a better solution out there.

Question

I can see two possible solutions, but I'm not sure how to achieve them:

  • There could be a way to ensure that RemoteIPAddress returns the remote IP address in the IPv4 shape that I expect.

  • It might be possible to always convert all IP addresses to this faux-IPv6 format, and if that conversion is idempotent, it would be a reasonable way to normalise all IP addresses before comparison.

How would I approach either of these solutions?

Is one objectively better than the other? (This should be an allowed question, because I'm not asking for personal opinions!)


Solution

  • Turns out option 2 was very simple: simply run .MapToIPv6() on both addresses before comparing. I think this might be the best solution, for the simple reason that it clearly will not cause any issues when/if this is used with IPv6 addresses too!