Last active
October 26, 2024 05:42
-
-
Save jjxtra/3b240b31a1ed3ad783a7dcdb6df12c36 to your computer and use it in GitHub Desktop.
C# / .NET core: Get Remote IP Address with Proxy / CDN Support
This file contains hidden or 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; | |
using System.Collections.Generic; | |
using System.IO; | |
using System.Linq; | |
using System.Net; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Http; | |
namespace HttpContext_RemoteIPAddress | |
{ | |
public static class HttpContextExtensions | |
{ | |
/// <summary> | |
/// Get remote ip address, optionally allowing for x-forwarded-for header check | |
/// </summary> | |
/// <param name="context">Http context</param> | |
/// <param name="allowForwarded">Whether to allow x-forwarded-for header check</param> | |
/// <returns>IPAddress</returns> | |
public static IPAddress GetRemoteIPAddress(this HttpContext context, bool allowForwarded = true) | |
{ | |
if (allowForwarded) | |
{ | |
// if you are allowing these forward headers, please ensure you are restricting context.Connection.RemoteIpAddress | |
// to cloud flare ips: https://www.cloudflare.com/ips/ | |
string header = (context.Request.Headers["CF-Connecting-IP"].FirstOrDefault() ?? context.Request.Headers["X-Forwarded-For"].FirstOrDefault()); | |
if (IPAddress.TryParse(header, out IPAddress ip)) | |
{ | |
return ip; | |
} | |
} | |
return context.Connection.RemoteIpAddress; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the gist. You can use this to also parse ip addresses with port information.