TCPDump-Buffer 上的 ReadLine 有时会阻塞,直到杀死 tcpdump

2024-05-10

我在 Android 应用程序中使用 TCPDump 时遇到问题。 它应该逐行读取 tcpdump 的输出并在我的应用程序中处理它。
问题是:
有时代码工作正常,它会立即读取捕获的数据包。但有时,ReadLine 会阻塞,直到我从 Linux 控制台终止 tcpdump 进程(killall tcpdump)。完成此操作后,我的循环会针对每一行进行处理(有时是 10 行,有时是 1 或 2 行)——这意味着 readLine 应该可以工作,但没有。
我读过类似的问题,但没有找到该问题的任何解决方案......
THANKS!!

public class ListenActivity extends Activity {

static ArrayList<Packet> packetBuffer = new ArrayList<Packet>();
static Process tcpDumpProcess = null;
static ListenThread thread = null;
public static final String TCPDUMP_COMMAND = "tcpdump -A -s0 | grep -i -e 'Cookie'\n";

private InputStream  inputStream = null;
private OutputStream outputStream = null;

@Override
protected void onStart() {
    super.onStart();
    try {
        tcpDumpProcess = new ProcessBuilder().command("su").redirectErrorStream(true).start();
        inputStream = tcpDumpProcess.getInputStream();
        outputStream = tcpDumpProcess.getOutputStream();
        outputStream.write(TCPDUMP_COMMAND.getBytes("ASCII"));
    } catch (Exception e) {
        Log.e("FSE", "", e);
    }
    thread = new ListenThread(new BufferedReader(new InputStreamReader(inputStream)));
    thread.start();
}

private class ListenThread extends Thread {

    public ListenThread(BufferedReader reader) {
        this.reader = reader;
    }

    private BufferedReader reader = null;

    @Override
    public void run() {

        reader = new BufferedReader(new InputStreamReader(inputStream));
        while (true) {
            try {                   
                String received = reader.readLine();
                Log.d("FS", received);
                Packet pReceived = Packet.analyze(received);
                if (pReceived != null) {
                    packetBuffer.add(pReceived);
                }
            } catch (Exception e) {
                Log.e("FSE", "", e);
            }

        }

    }

}

}


因为发送到管道的输出通常是块缓冲, 这俩tcpdump过程and the grep进程将等待,直到他们收到足够的数据才能将其发送到your程序。不过你很幸运,你选择使用的两个程序都准备修改它们的缓冲区行为(使用setvbuf(3)内部函数,以防您对细节感到好奇):

For tcpdump(8):

   -l     Make stdout line buffered.  Useful if you want to see
          the data while capturing it.  E.g.,
          ``tcpdump  -l  |  tee dat'' or ``tcpdump  -l   >
          dat  &  tail  -f  dat''.

For grep(1):

   --line-buffered
          Use line buffering on output.  This can cause a
          performance penalty.

尝试这个:

"tcpdump -l -A -s0 | grep --line-buffered -i -e 'Cookie'\n";
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

TCPDump-Buffer 上的 ReadLine 有时会阻塞,直到杀死 tcpdump 的相关文章

随机推荐