Search code examples
javapcapencoderdecoderjnetpcap

Encoding and Decoding of Pcap Packets


I need to convert packets to byte format and decode it . How is it possible to convert packets captured using jnetpcap library to array[bytes] and vice-versa in Java?


Solution

  • PcapPacket class has the method public int transferStateAndDataTo(byte[] buffer) which will copy the contents of the packet to the byte array.
    define the byte[] with size as packet.getTotalSize()

    if you are looking for the payload

    //opens an offline pcap file 
    Pcap pcap = Pcap.openOffline(pcapIpFile, errbuf); 
    
    //packet object
    PcapPacket packet = new PcapPacket(JMemory.POINTER); 
    
    Payload pl = new Payload();
    
    pcap.nextEx(packet);       // retrieves the next packet from input loop thru until eof
    
    if(packet.hasHeader(pl))  //this will check for and retrieve the payload
        pl.data()   // this will give you the data in the payload as a byte stream 
    

    for data in the different headers (ethernet/ip/tcp) there are other methods available with the implementation