Created
January 31, 2017 02:25
-
-
Save firelizzard18/74e7481fb97c16b90bfd801798f53319 to your computer and use it in GitHub Desktop.
`HttpContext.IsLocal()`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Net; | |
using Microsoft.AspNetCore.Http; | |
// use as you will, at your own risk | |
namespace Ouranos.Common.AspNetCore | |
{ | |
// adapted from http://stackoverflow.com/a/41242493 | |
public static class HttpContextExtensions | |
{ | |
public const string NullIPv6 = "::1"; | |
public static bool IsLocal(this ConnectionInfo conn) | |
{ | |
if (!conn.RemoteIpAddress.IsSet()) | |
return true; | |
// we have a remote address set up | |
// is local is same as remote, then we are local | |
if (conn.LocalIpAddress.IsSet()) | |
return conn.RemoteIpAddress.Equals(conn.LocalIpAddress); | |
// else we are remote if the remote IP address is not a loopback address | |
return conn.RemoteIpAddress.IsLoopback(); | |
} | |
public static bool IsLocal(this HttpContext ctx) | |
{ | |
return ctx.Connection.IsLocal(); | |
} | |
public static bool IsLocal(this HttpRequest req) | |
{ | |
return req.HttpContext.IsLocal(); | |
} | |
public static bool IsSet(this IPAddress address) | |
{ | |
return address != null && address.ToString() != NullIPv6; | |
} | |
public static bool IsLoopback(this IPAddress address) | |
{ | |
return IPAddress.IsLoopback(address); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment