Skip to content

Instantly share code, notes, and snippets.

@jjxtra
Last active October 26, 2024 05:42
Show Gist options
  • Select an option

  • Save jjxtra/3b240b31a1ed3ad783a7dcdb6df12c36 to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

Gostei

@borisgr04
Copy link
Copy Markdown

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
Copy Markdown

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
Copy Markdown

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
Copy Markdown

Thanks

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