使用jpcap获取完整的TCP数据包数据

时间:2013-07-28 08:58:47

标签: java pcap packet-sniffers sniffer jpcap

我使用jpcap教程中的一个简单程序。我想在端口4444上侦听我的其他客户端 - 服务器应用程序。我遇到了一个问题:方法TCPPacket.getTCPData()返回byte []数组,限制为30个元素。我知道数据包包含超过30个字节的有用数据,不包括TCP头字节。

如何获取超过30个字节的数据包数据?

我检查过,方法tcpPacket.getPayloadDataLength()返回超过500,而TCPPacket.getTCPData()返回一个30字节的数组......为什么只有30?

代码在这里

public class Test {
    public static void main(String[] args) {
        try {
            Test test = new Test(PacketCapture.lookupDevices()[5].trim().split("\\s")[0]);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }

    public Test(String device) throws Exception {
        // Initialize jpcap
        PacketCapture pcap = new PacketCapture();
        System.out.println("Using device '" + device + "'");
        pcap.open(device, true);
        pcap.setFilter("port 4444", true);
        pcap.addPacketListener(new PacketHandler());

        System.out.println("Capturing packets...");
        pcap.capture(-1); // -1 is infinite capturing
    }
}


class PacketHandler implements PacketListener {
    BufferedOutputStream stream;

    public PacketHandler() throws IOException {
        Path path = Paths.get("out.txt");
        stream = new BufferedOutputStream(
                Files.newOutputStream(path, StandardOpenOption.CREATE, StandardOpenOption.APPEND));
    }

    public void packetArrived(Packet packet) {
        try {
            // only handle TCP packets

            if(packet instanceof TCPPacket) {
                TCPPacket tcpPacket = (TCPPacket)packet;
                byte[] data;
                data = tcpPacket.getTCPData();
                stream.write(data);
                stream.write("\r\n----------\r\n".getBytes());
                stream.flush();
            }
        } catch( Exception e ) {
            e.printStackTrace(System.out);
        }
    }
}

1 个答案:

答案 0 :(得分:5)

而不是pcap.open(device, true);,请尝试pcap.open(device, 65535, true, 1000); jpcap的默认快照长度为96个字节,这意味着如果仅使用pcap.open(device, true); <打开,则只能获取数据包的前96个字节/ p>