How to get the client's IP automatically in ASP.NET CORE

Viewed 106

I want to find the user's IP without the user automatically submitting the request from the URL itself. When I do this locally, it returns the correct IP address, but when I publish the web service on the server, this IP becomes the server IP, what should I do?

For example, I have a service at the address https://test.com/api/GetAddress, I call this service in PostMan with the below code and it returns the user's IP address correctly, but when this service is on a site at the address https://sitetest.com/Dashboard/GetHome is called, the server address is returned and the user address is not given to me.

Note that I want to get this IP through the URL itself, because if I put this in the Request and it is received through the developer, it can give any IP to the Api.

I have used both types of code but still the same:

public static string GetClientIp()
    {
        try
        {
            string strHostName = System.Net.Dns.GetHostName();
            IPHostEntry ipHostInfo = Dns.Resolve(Dns.GetHostName());
            IPAddress ipAddress = ipHostInfo.AddressList
                .FirstOrDefault(a => a.AddressFamily == AddressFamily.InterNetwork);

            return ipAddress?.ToString();
        }
        catch (Exception ex)
        {
            return "0.0.0.0";
        }
        
        //return HttpContext.Current.Connection.RemoteIpAddress?.ToString() ?? "0.0.0.0";
    }
1 Answers

Inside a controller get the client ip address using:

var address = Request.HttpContext.Connection.RemoteIpAddress;

If you are using a reverse proxy then you have to use the Forwarded Headers Middleware. Example:

app.UseForwardedHeaders(new ForwardedHeadersOptions
{
    ForwardedHeaders = ForwardedHeaders.XForwardedFor | ForwardedHeaders.XForwardedProto
});

This is because the proxy forwards the request to your app so RemoteIpAdress has the ip address of the machine where the proxy is running. Most proxies usually set X-Forwarded-For header with the originating ip address. This middleware reads X-Forwarded-For header and sets the RemoteIpAdress correctly.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Forwarded-For

Related