简体   繁体   English

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

[英]Get full TCP packet data using jpcap

I use a simple program from jpcap tutorial. 我使用jpcap教程中的一个简单程序。 I want to listen on port 4444 to check my other client-server application. 我想在端口4444上侦听以检查我的其他客户端服务器应用程序。 And I've got a problem: method TCPPacket.getTCPData() returns byte[] array with limit in 30 elements. 我有一个问题:方法TCPPacket.getTCPData()返回byte []数组,其限制为30个元素。 I know that packets consist more then 30 bytes of useful data excluding TCP header bytes. 我知道数据包包含30字节以上的有用数据,不包括TCP头字节。

how can I fetch more then 30 bytes of packet data? 如何获取超过30个字节的数据包数据?

I checked, method tcpPacket.getPayloadDataLength() returns more then 500, and TCPPacket.getTCPData() returns an array of 30 bytes... Why only 30? 我检查了一下,方法tcpPacket.getPayloadDataLength()返回的值大于500,而TCPPacket.getTCPData()返回的数组为30个字节……为什么只有30个?

The code is here 代码在这里

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);
        }
    }
}

Instead of pcap.open(device, true); 代替pcap.open(device, true); , try pcap.open(device, 65535, true, 1000); ,请尝试pcap.open(device, 65535, true, 1000); The default snapshot length for jpcap is 96 bytes, which means you only get the first 96 bytes of a packet if you just open with pcap.open(device, true); jpcap的默认快照长度为96字节,这意味着,如果仅使用pcap.open(device, true);打开,则仅会获得数据包的前96个字节pcap.open(device, true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM