Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

在 Android 上實作 tcpdump 抓包應用

編輯:關於 Android 程式設計

Android 應用大量涉及網絡,當請求出錯時,抓包是定位問題最有效的手段。業界通常用 tcpdump 抓包,再用 Wireshark 分析產生的檔案。關於 tcpdump 的用法網路上有很多介紹,這裡不再贅述;Wireshark 的分析技巧也不是本文重點。

問題是每次都用 adb 下指令實在麻煩,所以我寫了一個應用把這些指令封裝起來。最根本的原理是透過 Runtime.exec 執行 Linux 指令。

運行結果

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 {
            // 把內附的 tcpdump 從 assets 複製到外部儲存空間
            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) {
        // 找出所有帶有 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 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) {
            try {
                int suProcessRetval = suProcess.waitFor();
                // 255 通常代表 su 授權失敗
                Log.d(TAG, "su exit value = " + suProcessRetval);
            } catch (Exception ex) {
                Log.w("Error running root command", 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\n" + "目標檔案: " + 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) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

說明與補充

手機必須已 Root。我沒有測試過未 Root 的情況,也只在自己的一台機器上驗證過,未能覆蓋所有機型。

另外有幾點值得補充。抓包工作一定要放在子執行緒,範例中已用 Thread 包好,這是因為 waitFor() 會長時間阻塞。tcpdump 二進位檔需與目標機器的 ABI 相符,arm 與 x86 不能混用,否則會出現 exec format error。cmd[0] 寫成 "adb shell" 其實不嚴謹——這裡是在裝置上執行,並沒有 adb 參與,實際作用是觸發 su 提權後的 shell 指令序列,寫成 "sh" 更貼切。輸出檔建議放在 /data/local 而非外部儲存,因為 SELinux 在較新版本上會阻擋 tcpdump 寫入 sdcard。參數說明:-p 不放入介面到混雜模式、-vv 詳細輸出、-s 0 抓完整封包不截斷、-w 指定輸出檔。

最後提醒,抓包涉及隱私與合規問題,請只用在自己的裝置與自己授權的流量上。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved