2014-01-15 45 views
0

我目前有一个RESTful C#web服务来获取客户端的IP地址。这工作正常,直到实现负载平衡。所以,现在Web服务正坐在负载平衡器后面。在C#中获取IP地址

现在,每次我尝试获取用户的IP地址时,我都会获取负载平衡器的IP地址。这里是代码的样子...

System.Web.HttpContext context = System.Web.HttpContext.Current; 
     if (context.Request.ServerVariables.AllKeys.Contains("HTTP_CLIENT_IP") && 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") && 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") && 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") && CheckIP(context.Request.ServerVariables["HTTP_FORWARDED_FOR"])) 
      return new Model(context.Request.ServerVariables["HTTP_FORWARDED_FOR"]); 

     if (context.Request.ServerVariables.AllKeys.Contains("HTTP_FORWARDED") && CheckIP(context.Request.ServerVariables["HTTP_FORWARDED"])) 
      return new Model(context.Request.ServerVariables["HTTP_FORWARDED"]); 

     return new Model(context.Request.ServerVariables["REMOTE_ADDR"]); 

尽管如此,我仍然最终得到错误的IP地址。有什么想法吗?想法?我错过了什么吗?

+0

你可以在未来的原始请求的痕迹?如果是这样,是否有任何标题包含原始IP地址?如果没有,你需要改变你的负载平衡器给你这个数据,否则你运气不好。如果是这样,只需要请求该头并获取数据。 – Tejs

+0

尝试HTTP标头的'X-Forwarded-For'。 – vcsjones

回答

4

性能良好的负载均衡器应在X_FORWARDED_FOR标头中放置一个或更多 IP地址。您的代码正在检查HTTP_FORWARDED_FOR和另外两个不太正确的变量。

并非所有的负载均衡器都表现良好,有些可以配置为包含该标头,如果它当前不在那里。

如果存在多个转发点,则标题中会有多个IP地址。在这种情况下,列出的第一个是客户端IP

X - 转发适用于:客户端,PROXY1,Proxy2将

+0

所以我尝试了这样的事情... string ip = context.Request.ServerVariables [“X_FORWARDED_FOR”]。Split(',')[0]; ...但这似乎不起作用。这是一个负载均衡问题吗? – prawn

+0

如果HTTP头中不存在X_FORWARDED_FOR,那么负载平衡器没有正确添加该头。您应该与负责管理负载均衡器的人讲话,并解释您的代码需要该标题。 –