5

I get server IP Address instead of client IP by using below method in ASP.NET CORE Web API . Please tell me where I'm going wrong. I have used ServerVariables["HTTP_X_FORWARDED_FOR"] in asp mvc before and that has worked correctly.

private string DetectIPAddress(HttpRequest request)
{
    var _IP = "RemoteIp:" + request.HttpContext.Connection.RemoteIpAddress.ToString() + " - LocalIpAddress:" +
                  request.HttpContext.Connection.LocalIpAddress;
    try
    {
        _IP += " IP.AddressFamily:" + Dns.GetHostEntry(Dns.GetHostName()).AddressList[1].ToString();

        _IP += " HostName:" + Dns.GetHostEntry(Dns.GetHostName()).HostName;

    }
    catch (Exception e)
    {

    }

    return _IP;
}
1

4 Answers 4

6

Getting the client IP sounds easy but in fact I've tried to get the client IP for many hours until I found this gist extension method in @Voodoo's comment that helped me. I want to make it more prominent and therefore create a separate answer. It works with .NET 5 on AWS fargate likely with some kind of load balancer pass-through where RemoteIpAddress alone does not work.

public static class HttpContextExtensions
{
    //https://gist.github.com/jjxtra/3b240b31a1ed3ad783a7dcdb6df12c36

    public static IPAddress GetRemoteIPAddress(this HttpContext context, bool allowForwarded = true)
    {
        if (allowForwarded)
        {
            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;
    }
}

Use it like this:

var ip = HttpContext.GetRemoteIPAddress().ToString();
Sign up to request clarification or add additional context in comments.

1 Comment

as usual for SO - the correct answer is the last in the list..
1

I using this method to get IP in .net core 3.1

    public static string GetIPAddress(HttpContext context)
    {
        if (!string.IsNullOrEmpty(context.Request.Headers["X-Forwarded-For"]))
        {
            return context.Request.Headers["X-Forwarded-For"];
        }
        return context.Connection?.RemoteIpAddress?.ToString();
    }

In Startup.cs add this code

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

Comments

0

In Asp.Net Core Web API to get Remote Client, IP Address is changed to the previous version of Asp.Net

Asp.Net Core introduced a new library for Http request and response.

Require the following namespace to add.

using Microsoft.AspNetCore.Http.Features;

Once, you added namespace then just need to add following a line of code for capture the Remote Client IP Address.

HttpContext.Features.Get()?.RemoteIpAddress?.ToString();

Note: When you try to run the application from the local system so above line of code return the result "::1" but it will work once you deploy your application somewhere

4 Comments

It dose not work.it retuns my server IP. log ipAddress192.168.160.1
I also add ForwardedHeadersOptions in statup.cs and it works correctly.Thanks a lot
HttpContext.Connection.RemoteIpAddress and HttpContext.Features.Get<IHttpConnectionFeature>()?.RemoteIpAddress give the same result. The correct answer here is ForwardedHeaders.
0

Use this line in your action method :

string ipAddress = HttpContext.Connection.RemoteIpAddress?.ToString();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.