Skip to content

Instantly share code, notes, and snippets.

@jjxtra
Last active December 18, 2023 08:28
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jjxtra/3b240b31a1ed3ad783a7dcdb6df12c36 to your computer and use it in GitHub Desktop.
Save jjxtra/3b240b31a1ed3ad783a7dcdb6df12c36 to your computer and use it in GitHub Desktop.
C# / .NET core: Get Remote IP Address with Proxy / CDN Support
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;
}
}
}
@Jair-Manuel
Copy link

Gostei

@borisgr04
Copy link

No funciona, devuelve
Ip Cliente: ::1 => _actionContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();

Ip Acceso Servidor: ::1 =>_actionContextAccessor.HttpContext.Connection.LocalIpAddress.ToString();

Ip Acceso GetRemoteIp: ::1 => _actionContextAccessor.HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();

@pfrmachado
Copy link

No funciona, devuelve
Ip Cliente: ::1 => _actionContextAccessor.HttpContext.Connection.RemoteIpAddress.ToString();

Ip Acceso Servidor: ::1 =>_actionContextAccessor.HttpContext.Connection.LocalIpAddress.ToString();

Ip Acceso GetRemoteIp: ::1 => _actionContextAccessor.HttpContext.Request.Headers["X-Forwarded-For"].FirstOrDefault();

você está rodando localmente? "::1" é o valor padrão neste caso.

@mtozlu
Copy link

mtozlu commented May 3, 2021

Thanks for the gist. You can use this to also parse ip addresses with port information.

if (IPEndPoint.TryParse(header, out IPEndPoint ip))
{
    return ip.Address;
}

@aijazbinqasim
Copy link

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment