Vivek Nuna
Vivek Nuna

Reputation: 1

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?)

Upvotes: 0

Views: 1212

Answers (2)

E.J. Brennan
E.J. Brennan

Reputation: 46839

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 "";
        }

    }

Upvotes: 1

Bruno Assis
Bruno Assis

Reputation: 1006

You are using .NET Standard, which doesn't contain the dependencies such as (HttpRequest and its extensions methods), therefore you'd need to either install the Nuget packages linked to HttpRequest OR convert your .NET standard project to a .NET WebApp. The former one contains the packages holding your HttpRequest.

Reference: HttpContext in .net standard library

Upvotes: 0

Related Questions