Cant Get the IP Address Of the client On my Published Website

398 views Asked by At

I have implemented a simple API that returns the ip address of the client "Request Sender". When I'm outside the network it always returns the same ip address when inside the network it works perfectly fine and it returns the local ip address of the device. The website is hosted on IIS the api logic is the following:

public static class iphelper
    {
        private const string HttpContext = "MS_HttpContext";
        private const string RemoteEndpointMessage = "System.ServiceModel.Channels.RemoteEndpointMessageProperty";

        public static string GetClientIpAddress(this HttpRequestMessage request)
        {
            if (request.Properties.ContainsKey(HttpContext))
            {
                dynamic ctx = request.Properties[HttpContext];
                if (ctx != null)
                {
                    return ctx.Request.UserHostAddress;
                }
            }

            if (request.Properties.ContainsKey(RemoteEndpointMessage))
            {
                dynamic remoteEndpoint = request.Properties[RemoteEndpointMessage];
                if (remoteEndpoint != null)
                {
                    return remoteEndpoint.Address;
                }
            }

            return null;
        }
    }
}

I have tried ALL of the Snippets out there all returns the same. My project uses ASP.NET MVC C#.

i tried HTTP_X_FORWARDED_FOR always return null

1

There are 1 answers

0
mjwills On BEST ANSWER

Most likely it is related to a load balancer or network device in front of your web server.

Given that:

REMOTE_ADDR reruns 192.168.130.140

I would suggest asking your Operations team what machine is running at that IP, and how it could pass through the calling IP Address (likely through X-Forwarded-For).