3

How can we get Client IP in .net core 6 web api. I have already implemented this in .net core 3, and 4 and never faced the problem, For some reason the code is not working in .net core 6, Instead of client IP, the code is giving Server IP. I have hosted this on an IIS.

Below is the code from program.cs

var builder = WebApplication.CreateBuilder(args);
builder.Services.Configure<ForwardedHeadersOptions>(options =>
{
    options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto;
});

//rest of the code follows

var app = builder.Build();
app.UseForwardedHeaders();

//rest of the code follows

Below is the code from the controller

string ip_address = Request.HttpContext.Connection.RemoteIpAddress?.ToString()

The above line is always giving me the IP address of the server where this web api is deployed, instead I need to IP address of the client from where the request has come.

Please let me know what is wrong here.

================================================================ Based on the early responses I received, Adding more information my question, My Web API is hosted behind a company firewall and the API is accessed from several networks outside of the company.

VIRIYALA NARESH
  • 187
  • 1
  • 4
  • 17
  • 1
    ClientIP is probably not available. Imagine if both the server and the client are behind a firewall/NAT, what would the client IP be? An unreliable method is to use the X-Forwarding headers, but it's never 100% accurate, and requires NAT/Firewall support to make it work. – Neil May 10 '22 at 15:01
  • On a IIS you do not have access to the machines resources like file system. The default connection to the host is a GUEST account. On client use DNS. See : https://learn.microsoft.com/en-us/dotnet/api/system.net.dns.gethostname?force_isolation=true&view=net-6.0 – jdweng May 10 '22 at 15:03
  • Neil, per your response, What I understand is there is no way we can get the client IP if the server is behind a firewall/NAT. I don't think that would be a case, Please confirm. Also I am looking for any code snippet which I can use to get the client IP – VIRIYALA NARESH May 10 '22 at 16:01
  • Better dupe [How can I get the clients IP address from HTTP headers?](https://stackoverflow.com/questions/527638/getting-the-client-ip-address-remote-addr-http-x-forwarded-for-what-else-coul). Tl;dr there is no reliable way to do this – Liam May 10 '22 at 16:03
  • If your code somehow results in server's IP instead of user's IP, my guess is that you are behind a Web proxy (not firewall). We have similar problem with Cloudflare but CF would provide `CF-Connecting-IP` to give the original IP. Your proxy needs to do something like that. – Luke Vo May 10 '22 at 16:20
  • As noted this is unreliable. There can be any number of reverse proxies and gateways between you and client. The best you can do is implement a fallback policy that includes one set of forward headers , another set, (yes there are many, some non-standard) and then relying on the IP closest to you. – Kit Mar 01 '23 at 01:24
  • Configuring x-forward header parsing is documented https://learn.microsoft.com/en-us/aspnet/core/host-and-deploy/proxy-load-balancer?view=aspnetcore-7.0 so long as you are careful to only use this configuration for upstream proxies you expect in production. – Jeremy Lakeman Jun 08 '23 at 01:01

1 Answers1

2

I am able to get the IP address from WebAPI controller this way:

 [HttpGet("api/GetIP")]
public async Task<IActionResult> GetIP()
{
    string ip = this.HttpContext.GetServerVariable("REMOTE_HOST");
    if (ip == null)
       {
          ip = this.HttpContext.GetServerVariable("REMOTE_ADDR");
       }
    return Ok($"IPAddress: {ip}");
}

I tested this on IIS and Azure, and it is in .net 6

I noticed that for me, Request.HttpContext.Connection.RemoteIpAddress gave the same result as my code above. Both return the IP address of the client, not the server where webapi resides.

I did not use this code in program.cs:

builder.Services.Configure(options => { options.ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto; });

It works without this code

Yogi
  • 410
  • 4
  • 16
  • Referrer is not enough when there are multiple reverse proxies and gateways, but this is a start in a fallback policy. – Kit Mar 01 '23 at 01:28
  • httpReferrer will always be null in this example – MC9000 Mar 07 '23 at 17:50
  • it is null or ::1 when you debug it in Visual Studio. But once you deploy it either to IIS or Azure, it will show you the IP Address. At least that's what I verified in my deployed application – Yogi Mar 07 '23 at 21:20
  • As long as the service is running inProcess it will work. If you host your app in a shared hosting "outofprocess"environment, it would not work. Here is a sample where I deployed this code in azure: https://testgetip.azurewebsites.net/api/GetIP – Yogi Mar 08 '23 at 00:18