0

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
  • 147
  • 1
  • 11
  • 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://docs.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

0 Answers0