Search code examples
asp.net-mvcasp.net-web-apiclass-library

Get client's IP Address in common c# Class Library for WebAPI and WebApplication


My business layer is common for WebApi and WebApplication. Need to track the client's IP address for each action. Searched on web and tried this but on development but I think this is for Server . I am getting server's ip address:

var host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName());
string ipAddress = host.AddressList[1].ToString();

Solution

  • You can try this extension method:

    public static class HttpContextExtensions
        {
            public static string GetIpAddress(this HttpContext httpContext)
            {
                try
                {
                    return httpContext.Connection.RemoteIpAddress.ToString();
                }
                catch
                {
                    return string.Empty;
                }
            }
        }
    

    older .Net version example:

    /// <summary>
            /// Gets the IP address for the current request, returns 0.0.0.0 if HttpsContext does not exist.
            /// </summary>
            /// <returns></returns>
            public static string GetIpAddress()
            {
                var context = HttpContext.Current;
                var ipAddress = String.Empty;
    
                if (context != null)
                {
                    ipAddress = context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
    
                    if (String.IsNullOrWhiteSpace(ipAddress))
                    {
                        ipAddress = context.Request.ServerVariables["REMOTE_ADDR"];
                    }
                    else
                    {
                        var ipAddresses = ipAddress.Split(new [] {','}, StringSplitOptions.RemoveEmptyEntries);
                        if (ipAddresses.Length > 0)
                        {
                            ipAddress = ipAddresses[0];
                        }
                    }
    
                    ipAddress = String.IsNullOrWhiteSpace(ipAddress) ? context.Request.UserHostName : ipAddress;
                }
                return String.IsNullOrWhiteSpace(ipAddress) ? "0.0.0.0" : ipAddress;
            }