获取客户端IP

/// <summary> ...... 
/// <summary> 
/// 获取当前请求的IP地址 
/// </summary> 
/// <returns></returns> 
public static string GetIP() 
{ 

   HttpRequest request = HttpContext.Current.Request;
   string ipAddress=string.Empty;
   if(request.ServerVariables["HTTP_X_FORWARDED_FOR"]==null || request.ServerVariables["HTTP_X_FORWARDED_FOR"]=="")     //使用了代理服务器
   {
      ipAddress = request.ServerVariables["REMOTE_ADDR"];     //没使用代理服务器,直接获取
   }
   else if(request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(",")>=0)
   {
      int index = request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(",");
      ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"].Substring(0,index-1);
   }
   else if(request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(";")>=0)
   {
      int index = request.ServerVariables["HTTP_X_FORWARDED_FOR"].IndexOf(";");
      ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"].Substring(0,index-1);
   }
   else
   {
      ipAddress = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
   } 
 return ipAddress; 
} 

posted @ 2011-03-14 10:48  第7笔画  阅读(326)  评论(3编辑  收藏  举报