2020-09-10 12:30:33 +00:00
|
|
|
using System.Net;
|
2020-07-17 15:06:52 +00:00
|
|
|
using Microsoft.AspNetCore.Http;
|
|
|
|
|
2020-07-18 15:54:23 +00:00
|
|
|
namespace MediaBrowser.Common.Extensions
|
2020-07-17 15:06:52 +00:00
|
|
|
{
|
|
|
|
/// <summary>
|
2020-07-18 15:54:23 +00:00
|
|
|
/// Static class containing extension methods for <see cref="HttpContext"/>.
|
2020-07-17 15:06:52 +00:00
|
|
|
/// </summary>
|
2020-07-18 15:54:23 +00:00
|
|
|
public static class HttpContextExtensions
|
2020-07-17 15:06:52 +00:00
|
|
|
{
|
|
|
|
/// <summary>
|
2020-09-10 12:16:41 +00:00
|
|
|
/// Checks the origin of the HTTP context.
|
2020-07-17 15:06:52 +00:00
|
|
|
/// </summary>
|
2020-09-10 12:16:41 +00:00
|
|
|
/// <param name="context">The incoming HTTP context.</param>
|
2020-09-02 10:22:14 +00:00
|
|
|
/// <returns><c>true</c> if the request is coming from LAN, <c>false</c> otherwise.</returns>
|
2020-09-10 12:16:41 +00:00
|
|
|
public static bool IsLocal(this HttpContext context)
|
2020-07-17 15:06:52 +00:00
|
|
|
{
|
2020-09-10 12:16:41 +00:00
|
|
|
return (context.Connection.LocalIpAddress == null
|
|
|
|
&& context.Connection.RemoteIpAddress == null)
|
|
|
|
|| context.Connection.LocalIpAddress.Equals(context.Connection.RemoteIpAddress);
|
2020-07-17 15:06:52 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
/// <summary>
|
2020-09-10 12:16:41 +00:00
|
|
|
/// Extracts the remote IP address of the caller of the HTTP context.
|
2020-07-17 15:06:52 +00:00
|
|
|
/// </summary>
|
2020-09-10 12:16:41 +00:00
|
|
|
/// <param name="context">The HTTP context.</param>
|
2020-09-02 10:22:14 +00:00
|
|
|
/// <returns>The remote caller IP address.</returns>
|
2021-03-23 16:16:10 +00:00
|
|
|
public static IPAddress GetNormalizedRemoteIp(this HttpContext context)
|
2020-07-17 15:06:52 +00:00
|
|
|
{
|
2020-09-10 12:30:33 +00:00
|
|
|
// Default to the loopback address if no RemoteIpAddress is specified (i.e. during integration tests)
|
|
|
|
var ip = context.Connection.RemoteIpAddress ?? IPAddress.Loopback;
|
2020-09-02 10:22:14 +00:00
|
|
|
|
|
|
|
if (ip.IsIPv4MappedToIPv6)
|
|
|
|
{
|
|
|
|
ip = ip.MapToIPv4();
|
|
|
|
}
|
|
|
|
|
2021-03-23 16:16:10 +00:00
|
|
|
return ip;
|
2020-07-17 15:06:52 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|