diff --git a/AMWD.Common.AspNetCore/Extensions/HttpContextExtensions.cs b/AMWD.Common.AspNetCore/Extensions/HttpContextExtensions.cs index 2bcc8ab..337a933 100644 --- a/AMWD.Common.AspNetCore/Extensions/HttpContextExtensions.cs +++ b/AMWD.Common.AspNetCore/Extensions/HttpContextExtensions.cs @@ -67,7 +67,7 @@ namespace Microsoft.AspNetCore.Http } if (!string.IsNullOrWhiteSpace(forwardedForAddress) && IPAddress.TryParse(forwardedForAddress, out var remoteAddress)) - return remoteAddress; + return remoteAddress.IsIPv4MappedToIPv6 ? remoteAddress.MapToIPv4() : remoteAddress; return httpContext.Connection.RemoteIpAddress; } diff --git a/CHANGELOG.md b/CHANGELOG.md index a610bba..e491f7a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Changed - Using `AddHostedService<>()` with "implementation factory" for `AddSingletonHostedService<>()` to resove singleton instance +- `GetRemoteIpAddress()` converts a mixed IPv4 address on IPv6 (e.g. `::ffff:127.0.0.1`) to a clean IPv4 address (e.g. `127.0.0.1`) ### Removed diff --git a/UnitTests/AspNetCore/Extensions/HttpContextExtensionsTests.cs b/UnitTests/AspNetCore/Extensions/HttpContextExtensionsTests.cs index 22ea737..568157a 100644 --- a/UnitTests/AspNetCore/Extensions/HttpContextExtensionsTests.cs +++ b/UnitTests/AspNetCore/Extensions/HttpContextExtensionsTests.cs @@ -188,6 +188,25 @@ namespace UnitTests.AspNetCore.Extensions Assert.AreEqual(header, result); } + [TestMethod] + public void ShouldReturnV4AddressOnMapped() + { + // arrange + remote = IPAddress.Parse("1.2.3.4"); + var header = IPAddress.Parse("::ffff:127.0.0.1"); + requestHeaders.Add("X-Forwarded-For", "::ffff:127.0.0.1"); + + var context = GetContext(); + + // act + var result = context.GetRemoteIpAddress(); + + // assert + Assert.AreNotEqual(remote, result); + Assert.AreNotEqual(header, result); + Assert.AreEqual(header.MapToIPv4(), result); + } + #endregion RemoteAddres #region Local Request