Android防火墙 监听流量

BroadcastReceiver模块

用于监听开机信息 并初始化和启动服务

[java]  view plain copy
  1. package zy.dnh;  
  2. import java.io.File;  
  3. import java.io.FileOutputStream;  
  4. import java.io.IOException;  
  5. import android.content.BroadcastReceiver;  
  6. import android.content.Context;  
  7. import android.content.Intent;  
  8. import android.widget.Toast;  
  9. public class getpowerinfo extends BroadcastReceiver{  
  10.     FileOutputStream out;  
  11.     final public String ONPATH = "/data/data/zy.dnh/on.txt";  
  12.     @Override  
  13.     public void onReceive(Context context, Intent intent) {  
  14.         // TODO Auto-generated method stub  
  15.            
  16.          if(intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){  
  17.                 Intent bootActivityIntent=new Intent(context,mService1.class);//启动服务  
  18.                 bootActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);  
  19.                 writefile("0,0,0,0,0,0,0,0,0,0,0,0",ONPATH);  
  20.                 context.startService(bootActivityIntent);  
  21.                  Toast.makeText(context, "Netcounter service has been lauched", Toast.LENGTH_LONG).show();  
  22.                  Api.applySavedIptablesRules(context, false);//应用防火墙规则  
  23.                  Toast.makeText(context, "Wall rules have been lauched", Toast.LENGTH_LONG).show();  
  24.          }  
  25.     }  
  26.     public void writefile(String str,String path )  
  27.     {  
  28.        File file;  
  29.        try {  
  30.           //创建文件  
  31.          file = new File(path);  
  32.           file.createNewFile();  
  33.             
  34.           //打开文件file的OutputStream  
  35.           out = new FileOutputStream(file);  
  36.           String infoToWrite = str;  
  37.           //将字符串转换成byte数组写入文件  
  38.           out.write(infoToWrite.getBytes());  
  39.           //关闭文件file的OutputStream  
  40.           out.close();  
  41.             
  42.             
  43.             
  44.        } catch (IOException e) {  
  45.           //将出错信息打印到Logcat  
  46.            
  47.             
  48.        }  
 

mService1模块

后台服务,用于维护流量日志

[java]  view plain copy
  1. public class mService1 extends Service  
  2. {  
  3.     
  4.     
  5.     private Handler objHandler = new Handler();  
  6.     private int intCounter=0;  
  7.     private int mHour;   
  8.     private int mMinute;   
  9.     private int mYear;   
  10.     private int mMonth;   
  11.     private int mDay;  
  12.     private String mdate;  
  13.       
  14.       
  15.     final public String DEV_FILE = "/proc/self/net/dev";//系统流量文件  
  16.     String[] ethdata={"0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0"};  
  17.     String[] gprsdata={"0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0"};  
  18.     String[] wifidata={"0","0","0","0","0","0","0","0","0","0","0","0","0","0","0","0"};  
  19.     String data="0,0,0,0,0,0,0,0,0,0,0,0";//对应on.txt里面的格式  
  20.     final String ETHLINE="  eth0";//以太网信息所在行  
  21.     final String GPRSLINE="rmnet0";  
  22.     final String WIFILINE="tiwlan0";  
  23.       
  24.     final String TEXT_ENCODING = "UTF-8";  
  25.        
  26.     final public String ONPATH = "/data/data/zy.dnh/on.txt";  
  27.     final public String LOGPATH = "/data/data/zy.dnh/log.txt";  
  28.       
  29.     private Runnable mTasks = new Runnable()   
  30.     {  
  31.      
  32.         public void run()//运行该服务执行此函数  
  33.         {  
  34.           refresh();  
  35.           
  36.           
  37.           intCounter++;  
  38.         // DisplayToast("Counter:"+Integer.toString(intCounter));  
  39.          objHandler.postDelayed(mTasks, 30000);//每3000毫秒执行一次  
  40.        }   
  41.     };  
  42.     
  43.   @Override  
  44.   public void onStart(Intent intent, int startId)  
  45.   {  
  46.     // TODO Auto-generated method stub  
  47.     //writefile("0,0,0,0,0,0,0,0,0,0,0,0",ONPATH);//每次启动服务 初始化onpath  
  48.       
  49.     objHandler.postDelayed(mTasks, 0);  
  50.     super.onStart(intent, startId);  
  51.   }  
  52.   @Override  
  53.   public void onCreate()  
  54.   {  
  55.     // TODO Auto-generated method stub  
  56.         
  57.     super.onCreate();  
  58.   }  
  59.     
  60.   @Override  
  61.   public IBinder onBind(Intent intent)  
  62.   {  
  63.     // TODO Auto-generated method stub  
  64.       
  65.       
  66.     return null;  
  67.   }  
  68.   @Override  
  69.   public void onDestroy()  
  70.   {  
  71.     // TODO Auto-generated method stub  
  72.       
  73.     /*  */  
  74.     objHandler.removeCallbacks(mTasks);  
  75.     super.onDestroy();  
  76.   }    
  77.   public void DisplayToast(String str)  
  78.   {  
  79.     Toast.makeText(this,str,Toast.LENGTH_SHORT).show();  
  80.   }    
  81.   public void readdev()  
  82.   {  
  83.       FileReader fstream = null;  
  84.     try {  
  85.           fstream = new FileReader(DEV_FILE);  
  86.             
  87.           }   
  88.         catch (FileNotFoundException e) {  
  89.             DisplayToast("Could not read " + DEV_FILE);  
  90.             
  91.         }  
  92.        BufferedReader in = new BufferedReader(fstream, 500);  
  93.        String line;  
  94.        String[] segs;  
  95.        String[] netdata;  
  96.          
  97.        int count=0;  
  98.        int k;  
  99.        int j;  
  100.        try {  
  101.           while ((line = in.readLine()) != null) {  
  102.               segs = line.trim().split(":");  
  103.               if(line.startsWith(ETHLINE))  
  104.                 {  
  105.                     
  106.                   netdata=segs[1].trim().split(" ");  
  107.                   for(k=0,j=0;k<netdata.length;k++)  
  108.                   {  
  109.                      if(netdata[k].length()>0)   
  110.                      {   
  111.                           
  112.                           ethdata[j]=netdata[k];  
  113.                           j++;  
  114.                      }  
  115.                   }  
  116.               }  
  117.               else if(line.startsWith(GPRSLINE))  
  118.               {  
  119.                    
  120.                 netdata=segs[1].trim().split(" ");  
  121.               for(k=0,j=0;k<netdata.length;k++)  
  122.               {  
  123.                  if(netdata[k].length()>0)   
  124.                  {   
  125.                         
  126.                       gprsdata[j]=netdata[k];  
  127.                       j++;  
  128.                  }  
  129.               }  
  130.               }  
  131.             else if(line.startsWith(WIFILINE))  
  132.           {  
  133.                
  134.             netdata=segs[1].trim().split(" ");  
  135.                 for(k=0,j=0;k<netdata.length;k++)  
  136.                 {  
  137.                     if(netdata[k].length()>0)   
  138.                     {   
  139.                       
  140.                       wifidata[j]=netdata[k];  
  141.                       j++;  
  142.                     }  
  143.                 }  
  144.           }  
  145.                
  146.                 
  147.                 
  148.                 
  149.               count++;  
  150.           }  
  151.           fstream.close();  
  152.              
  153.         }   
  154.         catch (IOException e) {  
  155.           DisplayToast(e.toString());  
  156.         }  
  157.   }  
  158.   public String getinfo(String path)  
  159.   {  
  160.     File file;  
  161.     String str="";   
  162.     FileInputStream in;  
  163.    try{  
  164.     //打开文件file的InputStream  
  165.      file = new File(path);  
  166.        in = new FileInputStream(file);  
  167.        //将文件内容全部读入到byte数组  
  168.        int length = (int)file.length();  
  169.        byte[] temp = new byte[length];  
  170.        in.read(temp, 0, length);  
  171.        //将byte数组用UTF-8编码并存入display字符串中  
  172.        str =  EncodingUtils.getString(temp,TEXT_ENCODING);  
  173.        //关闭文件file的InputStream  
  174.        in.close();  
  175.    }  
  176.    catch (IOException e) {  
  177.          
  178.       DisplayToast(e.toString());  
  179.          
  180.    }  
  181.     return str;  
  182.   }  
  183.   public void writefile(String str,String path )  
  184.   {  
  185.     File file;  
  186.     FileOutputStream out;  
  187.      try {  
  188.            //创建文件  
  189.          file = new File(path);  
  190.            file.createNewFile();  
  191.            //打开文件file的OutputStream  
  192.            out = new FileOutputStream(file);  
  193.            String infoToWrite = str;  
  194.            //将字符串转换成byte数组写入文件  
  195.            out.write(infoToWrite.getBytes());  
  196.            //关闭文件file的OutputStream  
  197.            out.close();   
  198.        } catch (IOException e) {  
  199.            //将出错信息打印到Logcat  
  200.           DisplayToast(e.toString());  
  201.              
  202.        }  
  203.   }  
  204.   public void refresh()  
  205.   {  
  206.         
  207.         
  208.       readdev();//读取本次开机之后直到当前系统的总流量  
  209.         
  210.        data=ethdata[0]+","+ethdata[1]+","+ethdata[8]+","+ethdata[9]+","  
  211.            +gprsdata[0]+","+gprsdata[1]+","+gprsdata[8]+","+gprsdata[9]+","  
  212.            +wifidata[0]+","+wifidata[1]+","+wifidata[8]+","+wifidata[9];  
  213.       String onstr=getinfo(ONPATH);//读取on.txt记录到onstr里  
  214.        String ondata[]=onstr.split(",");//将onstr各项分离 放到ondata里  
  215.       //计算增量  
  216.       int [] delta=new int [12];  
  217.         
  218.       delta[0]=Integer.parseInt(ethdata[0])-Integer.parseInt(ondata[0]);  
  219.       delta[1]=Integer.parseInt(ethdata[1])-Integer.parseInt(ondata[1]);  
  220.       delta[2]=Integer.parseInt(ethdata[8])-Integer.parseInt(ondata[2]);  
  221.       delta[3]=Integer.parseInt(ethdata[9])-Integer.parseInt(ondata[3]);  
  222.       delta[4]=Integer.parseInt(gprsdata[0])-Integer.parseInt(ondata[4]);  
  223.       delta[5]=Integer.parseInt(gprsdata[1])-Integer.parseInt(ondata[5]);  
  224.       delta[6]=Integer.parseInt(gprsdata[8])-Integer.parseInt(ondata[6]);  
  225.       delta[7]=Integer.parseInt(gprsdata[9])-Integer.parseInt(ondata[7]);  
  226.       delta[8]=Integer.parseInt(wifidata[0])-Integer.parseInt(ondata[8]);  
  227.       delta[9]=Integer.parseInt(wifidata[1])-Integer.parseInt(ondata[9]);  
  228.       delta[10]=Integer.parseInt(wifidata[8])-Integer.parseInt(ondata[10]);  
  229.       delta[11]=Integer.parseInt(wifidata[9])-Integer.parseInt(ondata[11]);  
  230.         
  231.         
  232.       //读取log.txt  
  233.     //获取当前时间  
  234.        final Calendar c = Calendar.getInstance();   
  235.       mYear = c.get(Calendar.YEAR); //获取当前年份   
  236.       mMonth = c.get(Calendar.MONTH)+1;//获取当前月份   
  237.       mDay = c.get(Calendar.DAY_OF_MONTH);//获取当前月份的日期号码   
  238.       mHour = c.get(Calendar.HOUR_OF_DAY);//获取当前的小时数   
  239.       mMinute = c.get(Calendar.MINUTE);//获取当前的分钟数     
  240.       mdate=mYear+"-"+mMonth+"-"+mDay;  
  241.         
  242.       String text=getinfo(LOGPATH);//将log.txt的内容读到text字符串中  
  243.       String [] line=text.split("/n");   
  244.        
  245.       String today=line[line.length-1];//获得今日已记录流量  
  246.       String [] beToday=today.split(",");   
  247.      //检查文件最后一行是否为今天的流量记录信息  
  248.       if(!beToday[0].equals(mdate))//  
  249.         //判断今日流量是否已经记录,如果今日流量没有记录  
  250.       {  
  251.        
  252.           text=text+mdate+",0,0,0,0,0,0,0,0,0,0,0,0/n";  
  253.           writefile(text,LOGPATH);  
  254.             
  255.             
  256.           line=text.split("/n");  
  257.           today=line[line.length-1];//获得今日已记录流量  
  258.            
  259.           beToday=today.split(",");   
  260.       }  
  261.       int i;  
  262.      //处理今日流量  
  263.       int [] newTodaydata=new int [12];//表示今日流量  
  264.       String newtoday=mdate;  
  265.       for(i=0;i<=11;i++)//更新今日流量  
  266.       {  
  267.           newTodaydata[i]=Integer.parseInt(beToday[i+1])+delta[i];  
  268.           newtoday=newtoday+","+newTodaydata[i];  
  269.       }  
  270.       newtoday=newtoday+"/n";  
  271.         
  272.         
  273.       String [] beTotal=line[0].split(",");  
  274.       int [] newTotaldata=new int [12];//表示总流量数值  
  275.       //更新第一行  
  276.       String newtotal="total";  
  277.       for(i=0;i<=11;i++)//更新今日流量和总流量  
  278.       {    
  279.           newTotaldata[i]=Integer.parseInt(beTotal[i+1])+delta[i];//总流量数值+delta[i]更新  
  280.           newtotal=newtotal+","+newTotaldata[i];  
  281.       }  
  282.       newtotal= newtotal+"/n";  
  283.       //处理中间不变的部分  
  284.       String before="";//before为之前的从第1行到昨天的流量记录  
  285.         
  286.       for(i=1;i<=line.length-2;i++)  
  287.         before=before+line[i]+"/n";//代表中间不变的部分  
  288.         
  289.       String newlog=newtotal+before+newtoday;  
  290.       writefile(data,ONPATH);//更新流量记录  
  291.       writefile(newlog,LOGPATH);//更新log*/  
  292.         
  293.         
  294.         
  295.   }  
  296.     
  297.     
  298. }  
 

 

应用iptable规则模块,通过运行iptable脚本来实现iptable规则的应用

[c-sharp]  view plain copy
  1. private static boolean applyIptablesRulesImpl(Context ctx, List<Integer> uids, boolean showErrors) {  
  2.                 if (ctx == null) {  
  3.                         return false;  
  4.                 }  
  5.                 final SharedPreferences prefs = ctx.getSharedPreferences(PREFS_NAME, 0);  
  6.                 final boolean whitelist = prefs.getString(PREF_MODE, MODE_WHITELIST).equals(MODE_WHITELIST);  
  7.                 boolean wifi = false// Wi-fi selected ?  
  8.                 final String itfs = prefs.getString(PREF_ITFS, ITF_3G);  
  9.                 String itfFilter;  
  10.                 if (itfs.indexOf("|") != -1) {  
  11.                         itfFilter = ""// Block all interfaces  
  12.                         wifi = true;  
  13.                 } else if (itfs.indexOf(ITF_3G) != -1) {  
  14.                         itfFilter = "-o rmnet+";;   
  15.                         // Block all rmnet interfaces  
  16.                 } else {  
  17.                         itfFilter = "-o tiwlan+";;  
  18.                         // Block all tiwlan interfaces  
  19.                         wifi = true;  
  20.                 }  
  21.     final StringBuilder script = new StringBuilder();  
  22.      try {  
  23.              int code;  
  24.         script.append("iptables -F || exit/n");  
  25.          final String targetRule = (whitelist ? "ACCEPT" : "REJECT");  
  26.         if (whitelist && wifi) {  
  27.                                 // When "white listing" Wi-fi, we need ensure that the dhcp and wifi users are allowed  
  28.                                 int uid = android.os.Process.getUidForName("dhcp");  
  29.             if (uid != -1) script.append("iptables -A OUTPUT "   
  30.                                         + itfFilter + " -m owner --uid-owner " + uid + " -j ACCEPT || exit/n");  
  31.               uid = android.os.Process.getUidForName("wifi");  
  32.             if (uid != -1) script.append("iptables -A OUTPUT " + itfFilter + " -m owner --uid-owner " + uid + " -j ACCEPT || exit/n"); }  
  33.           for (Integer uid : uids) {  
  34.              script.append("iptables -A OUTPUT " + itfFilter   
  35.                                         + " -m owner --uid-owner " + uid + " -j " + targetRule + " || exit/n");  
  36.                         }  
  37.            if (whitelist) {  
  38.                 script.append("iptables -A OUTPUT " + itfFilter + " -j REJECT || exit/n");  
  39.                         }  
  40.                 StringBuilder res = new StringBuilder();  
  41.              code = runScriptAsRoot(script.toString(), res);  
  42.              if (showErrors && code != 0) {  
  43.               String msg = res.toString();  
  44.               Log.e("DroidWall", msg);  
  45.                // Search for common error messages  
  46.               if (msg.indexOf("Couldn't find match `owner'") != -1 || msg.indexOf("no chain/target match") != -1) {  
  47.                alert(ctx, "Error applying iptables rules./nExit code: " + code + "/n/n" +"It seems your Linux kernel was not compiled with the netfilter /"owner/" module enabled, which is required for Droid Wall to work properly./n/n" +"You should check if there is an updated version of your Android ROM compiled with this kernel module.");  
  48.          } else {  
  49.            // Remove unnecessary help message from output  
  50.          if (msg.indexOf("/nTry `iptables -h' or 'iptables --help' for more information.") != -1) {  
  51.         msg = msg.replace("/nTry `iptables -h' or 'iptables --help' for more information.""");  
  52.        }  
  53.        // Try `iptables -h' or 'iptables --help' for more information.  
  54.           alert(ctx, "Error applying iptables rules. Exit code: " + code + "/n/n" + msg.trim());  
  55.            }  
  56.         } else {  
  57.            return true;  
  58.         }  
  59.        } catch (Exception e) {  
  60.       if (showErrors) alert(ctx, "error refreshing iptables: " + e);  
  61.                 }  
  62.                 return false;  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android流量上传下载监听开发是指通过监听网络流量的上传和下载情况,在Android应用程序中实时获取网络流量的使用情况。在开发过程中,可以使用TrafficStats类来实现对流量监听。 首先,需要在AndroidManifest.xml文件中添加相应的权限,以获取读取网络状态和网络信息的权限。 接下来,在应用程序的代码中,可以使用TrafficStats类提供的方法来获取网络流量的使用情况。例如,可以使用getUidRxBytes(int uid)和getUidTxBytes(int uid)方法来获取指定应用程序的上传流量和下载流量。 为了实时监听流量的变化,可以使用Handler和Timer的组合来定时获取流量的使用情况。首先,创建一个Handler对象来处理定时任务的回调方法。然后,使用Timer对象来创建一个定时任务,通过schedule方法来指定定时任务的执行时间间隔。在定时任务的run方法中,可以调用TrafficStats类的方法来获取流量的使用情况,并通过Handler对象发送消息来更新界面上显示的流量信息。 在应用程序中,可以通过TextView控件来显示流量上传和下载的信息。当接收到Handler对象发送的消息后,可以在消息处理方法中更新界面上的相关控件,显示最新的流量使用情况。 总结起来,Android流量上传下载监听开发是通过监听网络流量的上传和下载情况,在应用程序中实时获取并显示流量的使用情况。通过使用TrafficStats类提供的方法,可以获取指定应用程序的上传和下载流量。使用Handler和Timer的组合,可以定时获取并更新流量的使用情况,并通过界面上的控件显示最新的流量信息。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值