jellyfin/MediaBrowser.Common/Extensions/HttpContextExtensions.cs

42 lines
1.5 KiB
C#
Raw Normal View History

2020-09-10 08:30:33 -04:00
using System.Net;
2020-07-17 11:06:52 -04:00
using Microsoft.AspNetCore.Http;
2020-07-18 11:54:23 -04:00
namespace MediaBrowser.Common.Extensions
2020-07-17 11:06:52 -04:00
{
/// <summary>
2020-07-18 11:54:23 -04:00
/// Static class containing extension methods for <see cref="HttpContext"/>.
2020-07-17 11:06:52 -04:00
/// </summary>
2020-07-18 11:54:23 -04:00
public static class HttpContextExtensions
2020-07-17 11:06:52 -04:00
{
/// <summary>
/// Checks the origin of the HTTP context.
2020-07-17 11:06:52 -04:00
/// </summary>
/// <param name="context">The incoming HTTP context.</param>
2020-09-02 06:22:14 -04:00
/// <returns><c>true</c> if the request is coming from LAN, <c>false</c> otherwise.</returns>
public static bool IsLocal(this HttpContext context)
2020-07-17 11:06:52 -04:00
{
2022-12-05 09:00:20 -05:00
return (context.Connection.LocalIpAddress is null
&& context.Connection.RemoteIpAddress is null)
|| Equals(context.Connection.LocalIpAddress, context.Connection.RemoteIpAddress);
2020-07-17 11:06:52 -04:00
}
/// <summary>
/// Extracts the remote IP address of the caller of the HTTP context.
2020-07-17 11:06:52 -04:00
/// </summary>
/// <param name="context">The HTTP context.</param>
2020-09-02 06:22:14 -04:00
/// <returns>The remote caller IP address.</returns>
2023-02-17 13:27:36 -05:00
public static IPAddress GetNormalizedRemoteIP(this HttpContext context)
2020-07-17 11:06:52 -04:00
{
2020-09-10 08:30:33 -04: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 06:22:14 -04:00
if (ip.IsIPv4MappedToIPv6)
{
ip = ip.MapToIPv4();
}
return ip;
2020-07-17 11:06:52 -04:00
}
}
}