I use dotnet core 3.1 and I need the IP address of my website visitors, but when I try to get it, the IP of the server is returned, not the client. Here is the code I use:
var ip = _accessor.ActionContext.HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
This returns null. Then I tried to get my IP address using a third-party website. So I did this:
WebRequest request = WebRequest.Create("https://api.ipify.org/");
This will also return the IP address of the server, not the client. Then I tried this:
var host = Dns.GetHostEntry(Dns.GetHostName());
foreach (var ip in host.AddressList)
{
if (ip.AddressFamily == AddressFamily.InterNetwork)
{
return ip.ToString();
}
}
and this:
string localIP = string.Empty;
using (Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
{
socket.Connect("8.8.8.8", 65530);
IPEndPoint endPoint = socket.LocalEndPoint as IPEndPoint;
localIP = endPoint.Address.ToString();
}
but they return local IP addresses. return localIP.ToString();
And some codes line HTTPContext.Current.Request.UserHostAddress
or ServerVariables["REMOTE_ADDR"]
are not valid in dotnet core.
Any suggestion, please?