0

I'm trying to learn ASP.NET Core and I'm making a WhatismyIP website.

I've searched for a way to get the client IP address and I found HttpContext.GetServerVariable("REMOTE_ADDR") but for some reason it's always returning null.

I've also tried X-Forwarded-For but I've ended up having the same problem.

I have port forwarding on my router so I can access the web site from any network (it doesn't work even when I've tested it in the local network).

This is my code (I'm printing the IP for now to the console to test if the code works):

app.MapGet("/MainPage/", async (Context) => {
            string? IP = Context.GetServerVariable("REMOTE_ADDR");
            string? IP2 = Context.GetServerVariable("X-Forwarded-For");
            Console.WriteLine(IP);
            Console.WriteLine(IP2);

            await Context.Response.WriteAsync("Hello !");
});

I was expecting it to show the client IP address but it showed nothing (null). Do you have any idea why this is happening?

2
  • Not sure why you thought the variable REMOTE_ADDR should be available, I think it's only if you use IIS as the webserver. See learn.microsoft.com/en-us/dotnet/api/… Commented Jul 19, 2023 at 20:59
  • @Charlieface I've found those resources and solved the problem (you can see I wrote an answer) but thanks for the Help anyway !! Commented Jul 19, 2023 at 21:05

1 Answer 1

0

I've found a solution . According to this article , X-Forwarded-For only returns a value when the Client is behind a proxy server . I still don't understand why HttpContext.GetServerVariable("REMOTE_ADDR") didn't work . If you have any idea on why it didn't please write it in a comment .

anyway this is the solution I found :

//Gets the client's public IP address from a HttpContext Context.Connection.RemoteIpAddress

Sign up to request clarification or add additional context in comments.

1 Comment

From the link I quoted: "null if the server does not support the IServerVariablesFeature feature". Either way this seems to be the same as the duplicate question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.