Android tcpdump Clutch APP Implementation

Source: Internet
Author: User

 Android tcpdump clutch app Implementation 

Android application often involves the network, in the request network error, we can grasp the packet to analyze the network request, return data, etc., usually we use tcpdump this tool to capture the package, and then through the Wireshark tool to analyze the generated files, about Tcpdump, Can be looked up from the Internet, there are many introductions, such as: http://www.cnblogs.com/likwo/archive/2012/09/06/2673944.html. This article does not introduce how to use Wireshark to analyze files.

Using the ADB command to operate is still a bit cumbersome, so I wrote an application that encapsulates these commands. The most fundamental principle of implementation is to execute Linux commands through runtime.exec.

Run

Implementation code Commandshelper.java
/** * * @author lihong06 * @since 2014-3-3 */public class Commandshelper {private static final String NAME = "tcpdump    ";    private static final String TAG = "Commandshelper";        public static final String dest_file = environment.getexternalstoragedirectory () + "/capture.pcap";        public static Boolean Startcapture (context context) {InputStream is = null;        OutputStream OS = null;        Boolean retVal = false;            try {Assetmanager am = context.getassets ();            is = Am.open (NAME);            File sdcardfile = Environment.getexternalstoragedirectory ();            File Dstfile = new file (Sdcardfile, NAME);                        OS = new FileOutputStream (dstfile);                        CopyStream (is, OS);            string[] commands = new STRING[7];            Commands[0] = "adb shell";            Commands[1] = "SU";            COMMANDS[2] = "CP-RF" + dstfile.tostring () + "/data/local/tcpdump"; COMMANDS[3] = "Rm-r" + dstfile.tOstring ();            COMMANDS[4] = "chmod 777/data/local/tcpdump";            COMMANDS[5] = "cd/data/local";                        COMMANDS[6] = "Tcpdump-p-vv-s 0-w" + dest_file;        ExecCmd (commands);            } catch (IOException e) {e.printstacktrace ();        LOG.I (TAG, "error:" + e.getmessage ());            } finally {closesafely (IS);        closesafely (OS);    } return retVal; public static void Stopcapture (context context) {//Find all processes with tcpdump string[] commands = new Stri        NG[2];        Commands[0] = "adb shell";        COMMANDS[1] = "Ps|grep tcpdump|grep Root|awk ' {print $} '";        Process process = execcmd (commands);        String result = Parseinputstream (Process.getinputstream ()); if (!            Textutils.isempty (Result)) {string[] PIDs = result.split ("\ n");                if (null! = PIDs) {string[] Killcmds = new String[pids.length]; for (int i = 0; i < pids.length;                ++i) {Killcmds[i] = "kill-9" + pids[i];            } execcmd (KILLCMDS); }}} public static Process execcmd (String command) {return execcmd (new string[] {command}, Tru    e);    public static Process ExecCmd (string[] commands) {return ExecCmd (commands, true);        public static Process ExecCmd (string[] commands, Boolean waitFor) {process suprocess = null;            try {suprocess = Runtime.getruntime (). EXEC ("su");            DataOutputStream OS = new DataOutputStream (Suprocess.getoutputstream ()); for (String cmd:commands) {if (!                Textutils.isempty (cmd)) {os.writebytes (cmd + "\ n");            }} os.flush ();            Os.writebytes ("exit\n");        Os.flush ();        } catch (IOException e) {e.printstacktrace (); } if (WaitFor) {boolEAN retval = false;                try {int suprocessretval = suprocess.waitfor ();                if (255! = suprocessretval) {retval = true;                } else {retval = false;            }} catch (Exception ex) {LOG.W ("Error ejecutando el comando Root", ex);    }} return suprocess;        } private static void CopyStream (InputStream is, OutputStream OS) {final int buffer_size = 1024;            try {byte[] bytes = new Byte[buffer_size]; for (;;)                {int count = is.read (bytes, 0, buffer_size);                if (count = =-1) {break;            } os.write (Bytes, 0, count);        }} catch (IOException e) {e.printstacktrace (); }} private static void Closesafely (Closeable is) {try {if (null! = is) {is.     Close ();       }} catch (IOException e) {e.printstacktrace (); }} private static String Parseinputstream (InputStream is) {InputStreamReader ISR = new Inputstreamreade        R (IS);        BufferedReader br = new BufferedReader (ISR);        String line = null;        StringBuilder sb = new StringBuilder ();            try {while (line = Br.readline ())! = null) {Sb.append (line). append ("\ n");        }} catch (IOException e) {e.printstacktrace ();    } return sb.tostring (); }}

Mainactivity.java
public class Mainactivity extends Activity {@Override protected void onCreate (Bundle savedinstancestate) {s        Uper.oncreate (savedinstancestate);                Setcontentview (R.layout.activity_main);        Final TextView TextView = (TextView) Findviewbyid (R.ID.TEXTVIEW1);        String OldText = Textview.gettext (). toString ();                Textview.settext (OldText + "\ n" + "target file:" + commandshelper.dest_file); Findviewbyid (r.id.start_capture). Setonclicklistener (New View.onclicklistener () {@Override public vo                ID OnClick (View v) {v.setenabled (false); New Thread (New Runnable () {@Override public void run () {fin                        Al Boolean retVal = Commandshelper.startcapture (mainactivity.this);                                Runonuithread (New Runnable () {@Override public void run () { Toast.makeText (Mainactivity.this, "startcapture result =" + RetVal, Toast.length_short). Show ();                    }                        });            }}). Start ();                }        }); Findviewbyid (r.id.stop_capture). Setonclicklistener (New View.onclicklistener () {@Override public voi                D OnClick (View v) {commandshelper.stopcapture (mainactivity.this);            Findviewbyid (r.id.start_capture). SetEnabled (True);    }        }); } @Override Public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu, this adds items to the Actio        n Bar if it is present.        Getmenuinflater (). Inflate (R.menu.main, menu);    return true; }}

Description1, the phone must be root, no root I have not tested, in addition, I have only tested a cell phone, no coverage to all mobile phones. 2, if you find the problem, please tell me, thank you.

Android tcpdump Clutch APP Implementation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.