title: Getting IP Address in C#
body: <p>I currently have a RESTful C# web service that gets the client's IP address. This was working fine until load-balancing was implemented. So now the web service is sitting behind a load balancer.</p>
  
  <p>Now, every time I try to get the user's IP address, I get the IP address of the load balancer instead. Here is what the code looks like...</p>
  
  <pre><code>System.Web.HttpContext context = System.Web.HttpContext.Current;
          if (context.Request.ServerVariables.AllKeys.Contains("HTTP_CLIENT_IP") &amp;&amp; CheckIP(context.Request.ServerVariables["HTTP_CLIENT_IP"]))
              return new Model(context.Request.ServerVariables["HTTP_CLIENT_IP"]);
  
          if (context.Request.ServerVariables.AllKeys.Contains("HTTP_X_FORWARDED_FOR"))
              foreach (string ip in context.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].Split(','))
                  if (CheckIP(ip.Trim()))
                      return new Model(ip.Trim());
  
          if (context.Request.ServerVariables.AllKeys.Contains("HTTP_X_FORWARDED") &amp;&amp; CheckIP(context.Request.ServerVariables["HTTP_X_FORWARDED"]))
              return new Model(context.Request.ServerVariables["HTTP_X_FORWARDED"]);
  
          if (context.Request.ServerVariables.AllKeys.Contains("HTTP_X_CLUSTER_CLIENT_IP") &amp;&amp; CheckIP(context.Request.ServerVariables["HTTP_X_CLUSTER_CLIENT_IP"]))
              return new Model(context.Request.ServerVariables["HTTP_X_CLUSTER_CLIENT_IP"]);
  
          if (context.Request.ServerVariables.AllKeys.Contains("HTTP_FORWARDED_FOR") &amp;&amp; CheckIP(context.Request.ServerVariables["HTTP_FORWARDED_FOR"]))
              return new Model(context.Request.ServerVariables["HTTP_FORWARDED_FOR"]);
  
          if (context.Request.ServerVariables.AllKeys.Contains("HTTP_FORWARDED") &amp;&amp; CheckIP(context.Request.ServerVariables["HTTP_FORWARDED"]))
              return new Model(context.Request.ServerVariables["HTTP_FORWARDED"]);
  
          return new Model(context.Request.ServerVariables["REMOTE_ADDR"]);
  </code></pre>
  
  <p>Despite this, I am still ultimately getting the wrong IP address. Any thoughts? Ideas? Am I missing something?</p>