gpt4 book ai didi

java - 如何在Java中运行tshark来实时获取数据包?

转载 作者:行者123 更新时间:2023-11-30 08:00:54 29 4
gpt4 key购买 nike

我在 Java 中运行 tshark 时遇到问题。数据包似乎是批量到达的,而不是真正实时的(就像从终端运行时发生的那样)。我尝试了几种不同的方法:

ArrayList<String> command = new ArrayList<String>();
command.add("C:\\Program Files\\Wireshark\\tshark.exe");
ProcessBuilder pb = new ProcessBuilder(command);
Process process = pb.start();

BufferedReader br = null;
try {
//tried different numbers for BufferedReader's last parameter
br = new BufferedReader(new InputStreamReader(process.getInputStream()), 1);
String line = null;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch...

还尝试使用InputStream的available()方法,如What does InputStream.available() do in Java?中所示。

我还使用以下代码尝试了 NuProcess 库:

NuProcessBuilder pb = new NuProcessBuilder(command);
ProcessHandler processHandler = new ProcessHandler();
pb.setProcessListener(processHandler);
NuProcess process = pb.start();
try {
process.waitFor(0, TimeUnit.SECONDS);
} catch (InterruptedException e) {
e.printStackTrace();
}

private class ProcessHandler extends NuAbstractProcessHandler {
private NuProcess nuProcess;

@Override
public void onStart(NuProcess nuProcess) {
this.nuProcess = nuProcess;
}

@Override
public void onStdout(ByteBuffer buffer) {
if (buffer == null)
return;

byte[] bytes = new byte[buffer.remaining()];
buffer.get(bytes);
System.out.println(new String(bytes));
}
}

这些方法都不起作用。仅当嗅探到大约 50 个数据包时,数据包才会始终到达,就好像已缓冲一样。

您知道为什么会发生这种情况以及如何解决吗?这真是令人沮丧。我花了很多时间在 SO 上查看类似的问题,但没有一个有帮助。

您发现我的代码中有任何错误吗?它适用于您的情况吗?

最佳答案

正如 tshark 手册页所述:

   −l  Flush the standard output after the information for each packet is
printed. (This is not, strictly speaking, line‐buffered if −V was
specified; however, it is the same as line‐buffered if −V wasn’t
specified, as only one line is printed for each packet, and, as −l
is normally used when piping a live capture to a program or script,
so that output for a packet shows up as soon as the packet is seen
and dissected, it should work just as well as true line‐buffering.
We do this as a workaround for a deficiency in the Microsoft Visual
C++ C library.)

This may be useful when piping the output of TShark to another
program, as it means that the program to which the output is piped
will see the dissected data for a packet as soon as TShark sees the
packet and generates that output, rather than seeing it only when
the standard output buffer containing that data fills up.

尝试使用 -l 命令行参数运行 tshark。

关于java - 如何在Java中运行tshark来实时获取数据包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31931729/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com