javapcappacket-snifferssnifferjpcap

Get full TCP packet data using jpcap


I use a simple program from jpcap tutorial. I want to listen on port 4444 to check my other client-server application. And I've got a problem: method TCPPacket.getTCPData() returns byte[] array with limit in 30 elements. I know that packets consist more then 30 bytes of useful data excluding TCP header bytes.

how can I fetch more then 30 bytes of packet data?

I checked, method tcpPacket.getPayloadDataLength() returns more then 500, and TCPPacket.getTCPData() returns an array of 30 bytes... Why only 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);
        }
    }
}

Solution

  • Instead of pcap.open(device, true);, try 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);