Changing GetRemoteIpAddress() to resolve clean IPv4 or IPv6 addresses from headers
This commit is contained in:
@@ -67,7 +67,7 @@ namespace Microsoft.AspNetCore.Http
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (!string.IsNullOrWhiteSpace(forwardedForAddress) && IPAddress.TryParse(forwardedForAddress, out var remoteAddress))
|
if (!string.IsNullOrWhiteSpace(forwardedForAddress) && IPAddress.TryParse(forwardedForAddress, out var remoteAddress))
|
||||||
return remoteAddress;
|
return remoteAddress.IsIPv4MappedToIPv6 ? remoteAddress.MapToIPv4() : remoteAddress;
|
||||||
|
|
||||||
return httpContext.Connection.RemoteIpAddress;
|
return httpContext.Connection.RemoteIpAddress;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
- Using `AddHostedService<>()` with "implementation factory" for `AddSingletonHostedService<>()` to resove singleton instance
|
- 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
|
### Removed
|
||||||
|
|
||||||
|
|||||||
@@ -188,6 +188,25 @@ namespace UnitTests.AspNetCore.Extensions
|
|||||||
Assert.AreEqual(header, result);
|
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
|
#endregion RemoteAddres
|
||||||
|
|
||||||
#region Local Request
|
#region Local Request
|
||||||
|
|||||||
Reference in New Issue
Block a user