Android tcpdump Packet Capture Application Implementation

Source: Internet
Author: User

Network is often involved in Android applications. When an error occurs in the request network, we can capture packets to analyze network requests and returned data. We usually use tcpdump to capture packets, the wireshark tool is used to analyze the generated files. For more information about tcpdump, visit the Internet, 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 adb commands is still troublesome, so I wrote an application and encapsulated these commands. The most fundamental principle is to execute linux commands through runtime.exe c.

Run

,

Implementation Code CommandsHelper. java <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> Vc3Ryb25nPgo8cHJlIGNsYXNzPQ = "brush: 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; OutputSt Ream 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 () + "/dat A/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 (Co Ntext context) {// find all the processes with tcpdump String [] commands = new String [2]; commands [0] = "adb shell "; commands [1] = "ps | grep tcpdump | grep root | awk '{print $2}'"; 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}, true);} public static Process execCmd (String [] commands) {return execCmd (commands, true );} public static Process execCmd (String [] commands, boolean wai TFor) {Process suProcess = null; try {suProcess = runtime.getruntime(cmd.exe c ("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 InputStreamReader (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) {super. 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 void onClick (View v) {v. setEnabled (false); new Thread (new Runnable () {@ Override public void run () {final 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 void 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 action bar if it is present. getMenuInflater (). inflate (R. menu. main, menu); return true ;}}

Description1. The mobile phone must be Root. I have never tested it without root. In addition, I only tested one of my mobile phones and did not cover all the mobile phones. 2. If any problem is found, please contact me. Thank you.




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.