Search code examples
javabytebytearrayoutputstream

How is this 13 bytes long?


Two quotes:

All of the remaining messages in the protocol take the form of <length prefix><message ID><payload>. The length prefix is a four byte big-endian value. The message ID is a single decimal byte. The payload is message dependent.

request: <len=0013><id=6><index><begin><length> 

The request message is fixed length, and is used to request a block. The payload contains the following information:

  • index: integer specifying the zero-based piece index
  • begin: integer specifying the zero-based byte offset within the piece
  • length: integer specifying the requested length.

When I write everything it sums up to 5 bytes. Using

ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
byteStream.write( 13 );
byteStream.write( 6 );
byteStream.write( index );
byteStream.write( begin );
byteStream.write( length );

message = byteStream.toByteArray();

EDIT: Sorry i was kind of pissed when i wrote it. its the bittorent protocol. Using this spec.


Solution

  • The write() method writes one byte.

    If you send it a char or int it just strips everything above the 8th bit with & 0xFF.

    You have more options with DataOutputStream (writeInt, writeShort etc.) but it uses big endian byte order so you might need to perform an Integer.reverseBytes() (or Short.reverseBytes()) call before passing in the value to the writeXYZ() method.

    ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
    
    DataOutputStream dout = new DataOutputStream(byteStream);
    
    dout.writeInt( 0x13 ); // L:4
    dout.write( 6 ); // L:5
    dout.writeShort( index ); // guess, L:7
    dout.writeLong( begin ); // >4GB support? L:15
    dout.writeInt( length ); // clients accept below to 2^17, L:19
    
    dout.flush(); // to be sure
    
    message = byteStream.toByteArray();
    

    Remark: The spec doesn't state the length of index, begin and length. I just wanted to give a sample of the available options.

    Edit 2: Edited the sample based on D.Shawley's answer and a spec found here.