Search code examples
c#.net.net-standard

How to get the client's ip address in .net standard?


I need to get the client's IP address in .net standard 2.1 class library application.

I am using the code below, It works as expected in the .net framework, but its giving compilation error in .net standard.

private string IPAddress { get { return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; } }

Error CS1061 'HttpRequest' does not contain a definition for 'ServerVariables' and no accessible extension method 'ServerVariables' accepting a first argument of type 'HttpRequest' could be found (are you missing a using directive or an assembly reference?)


Solution

  • I have used this and works for me:

        public static string GetLocalIpAddress()
        {
            try
            {
                using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, 0))
                {
                    socket.Connect("8.8.8.8", 65530);
                    var endPoint = socket.LocalEndPoint as IPEndPoint;
                    Logger.LogMessage("Local Ip Address detected: " + endPoint.Address.ToString());
                    return endPoint.Address.ToString();
                }
            }
            catch (Exception ex)
            {
                Logger.LogMessage(null, "Error obtaining local ip address:" + ex.Message);
                return "";
            }
    
        }