C#实现ip 地址过滤功能

时间:2022-08-29 16:55:58

C#实现ip 地址过滤功能

[ 2005-07-11 12:21:55 | 作者: admin ]
字体大小: | |
 实现思想,比如219.221.105.1-219.221.105.31

通过函数将其变为2192211051和21922110531,当然ip是21.15.2.1时候,要在前面加0,我的public string sss(string s)就是实现这个,可以看看,测试通过!

   string proxy,Getip;;

   //string realip;;

   //realip = Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();;//返回空表示没有用代理,否则返回代理服务ip

   proxy = Request.ServerVariables["REMOTE_ADDR"].ToString();;//没用代理

   //if(realip == "")

   Getip = proxy;;

   //else

   //Getip = realip;;

   string[] ip_user_arr = Getip.Split('.');;

   DBReader db = new DBReader();; //从数据库中读取ip起始地址和结束地址

   DataSet ds = new DataSet();;

   ds = db.Select("Select * from IPcontrol where 1=1");;

   string[] ipstar = new string[ds.Tables[0].Rows.Count];;

   string[] ipend = new string[ds.Tables[0].Rows.Count];;

   for(int i = 0;; i 〈 ds.Tables[0].Rows.Count;; i++)

   {

   ipstar[i] = sm.Decrypto(ds.Tables[0].Rows[i]["IPAccessStar"].ToString());;//因为ip用了加密算法的,所以调用了sm.Decrpto函数

   ipend[i] = sm.Decrypto(ds.Tables[0].Rows[i]["IPAccseeEnd"].ToString());;

   }

   if((ipstar.Length == ipend.Length) && ipstar.Length 〉0)

   {

   for(int j = 0;;j〈ipstar.Length;; j++)

   {

   string ip_start = ipstar[j];;

   string ip_end = ipend[j];;

   string[] ip_start_arr = ip_start.Split('.');;

   string[] ip_end_arr = ip_end.Split('.');;

   string ip_start_str = "",ip_end_str = "",ip_user_str = "";;

   for(int i = 0;;i〈4;;i++)

   {

   ip_start_str += this.sss(Convert.ToString((Convert.ToDouble(ip_start_arr[i])/1000)));;

   ip_end_str += this.sss(Convert.ToString((Convert.ToDouble(ip_end_arr[i])/1000)));;

   ip_user_str += this.sss(Convert.ToString((Convert.ToDouble(ip_user_arr[i])/1000)));;

   }

   if(Convert.ToDouble(ip_user_str)〉Convert.ToDouble(ip_end_str) || Convert.ToDouble(ip_user_str)〈Convert.ToDouble(ip_start_str))

   {

   //Response.Write( "〈script language='javascript'〉alert('您的IP不在允许访问的IP列表中!');;〈/script〉");;

   }

  

   }

   //IP符合条件时候处理

   }

   else

   {

   //数据库没有ip地址过滤表时的处理

   //Response.Write( "〈script language='javascript'〉alert('您的IP不在允许访问的IP列表中!');;〈/script〉");;

   }

public string sss(string s)

  {

   int i = s.IndexOf('.');;

   string temp = s.Substring(i+1, s.Length - i - 1);;

   while(temp.Length 〈 3)

   {

   temp += "0";;

   }

   return temp;;

  }