I am implementing the BitTorent protocol using Java via this spec. In the messages section all messages are fixed length except 2 of them; for one of them it's the only variable message after the handshake so I can check others and assume it's a piece message when no other messages met. But for the following message
bitfield: <len=0001+X><id=5><bitfield>
The bitfield message may only be sent immediately after the handshaking sequence is completed, and before any other messages are sent. It is optional, and need not be sent if a client has no pieces.
The bitfield message is variable length, where X is the length of the bitfield. The payload is a bitfield representing the pieces that have been successfully downloaded. The high bit in the first byte corresponds to piece index 0. Bits that are cleared indicated a missing piece, and set bits indicate a valid and available piece. Spare bits at the end are set to zero.
A bitfield of the wrong length is considered an error. Clients should drop the connection if they receive bitfields that are not of the correct size, or if the bitfield has any of the spare bits set.
I can't come up with a way to parse it if i do not know the length; how am I supposed to locate id in a stream of bytes?
Edit: In payload of the bitfield message is the 0's or 1's for each piece in the torrent file, length of the message will change depending on the size of the torrent content. So i don't think i can assume that the number of pieces will always fit in a 5 byte number.