Copied from: https://stackoverflow.com/a/79473620/8216122 simply call: string sIP = await GetClientIP.ClientIP();
using System.Net.Sockets;
using System.Net;
public static class GetClientIP
{
private static HttpContext _httpContext => new HttpContextAccessor().HttpContext;
public static async Task<string> ClientIP()
{
string sClientIP = String.Empty;
IPAddress? ip = _httpContext.Connection.RemoteIpAddress;
if (ip != null) {
if (ip.AddressFamily == AddressFamily.InterNetworkV6) {
ip = Dns.GetHostEntry(ip).AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork);
}
sClientIP = ip.ToString();
}
return sClientIP;
}
}