1

I use dotnet core 3.1 and I need the IP address of my website visitors, but when I try to get it, the IP of the server is returned, not the client. Here is the code I use:

var ip = _accessor.ActionContext.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();

This returns null. Then I tried to get my IP address using a third-party website. So I did this:

WebRequest request = WebRequest.Create("https://api.ipify.org/");

This will also return the IP address of the server, not the client. Then I tried this:

var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
    if (ip.AddressFamily == AddressFamily.InterNetwork)
    {
        return ip.ToString();
    }
}

and this:

string localIP = string.Empty;
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
    socket.Connect("8.8.8.8", 65530);
    IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
    localIP = endPoint.Address.ToString();
}

but they return local IP addresses. return localIP.ToString();

And some codes line HTTPContext.Current.Request.UserHostAddress or ServerVariables["REMOTE_ADDR"] are not valid in dotnet core. Any suggestion, please?

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Rex Kax
  • 11
  • 1
  • 2
    Does this answer your question? [How do I get client IP address in ASP.NET CORE?](https://stackoverflow.com/questions/28664686/how-do-i-get-client-ip-address-in-asp-net-core) (Check all answers, not only the accepted one) – Stephan Bauer Jul 26 '21 at 06:51
  • I use this: `string ipAddress = Request.HttpContext.Connection?.RemoteIpAddress?.ToString();` – Catalin Jul 26 '21 at 06:52
  • @StephanBauer This returns null; I did config my startup.cs file, but in vain. – Rex Kax Jul 26 '21 at 06:53
  • @Catalin This returns null as well, dear friend. – Rex Kax Jul 26 '21 at 06:54
  • just try to add Microsoft.AspNetCore.HttpOverrides NuGet package and use it according to this document: https://www.thecodebuzz.com/get-ip-address-in-asp-net-core-guidelines/ . I hop it help you – masoud Jul 26 '21 at 07:16

1 Answers1

0

I'm assuming that you are running the website not by directly exposing Kesterl to the end clients but under some reverse proxy (IIS/nginx). In that case for Connection.RemoteIpAddress to work property you have to configure the application by adding something like following code in the startup:

app.UseForwardedHeaders(new ForwardedHeadersOptions { ForwardedHeaders = ForwardedHeaders.XForwardedFor })
Grigoryants Artem
  • 1,401
  • 2
  • 15
  • 32