bittorrenttorrent

Does the length field in a peer TCP message includes the length of itself or just the length of every byte afterwards?


I work on a BitTorrent client and I now need to send messages to my peers (bitfield, interested, etc).

While parsing and building structs I need to include the first field which is len - the length of the message I send.

Let's assume I want to send an interested message. I need to send a 5 byte struct: First 4 bytes are the len field containing the length of the message, and the 5th byte contains the message id (interested = 2).

To my understanding, I need to put 5 in the len field as the total of the length of the message is 5 bytes.

However, according to The Theory Org, the len field should contain the value 1. I think the reasoning for that is when I read the buffer, I read first 4 bytes as the length (the value of which is 1), and then I read the buffer again (this time: only the first one byte) to gather the message is.

So which is right? Thank you!


Solution

  • Length is not included. Length is just showing how many bytes are after the length 4 bytes prefix.

    Remember: message-id always occupy only 1 byte(!), all other indexes are integers and integers always occupy 4 bytes.

    Let me show you how to understand those message lengths from Theory org which you shared in the post:

    have: <len=0005><id=4> 4 bytes for length, 1 byte for id, 4 bytes for piece index. ie: 0005 = 1 byte for id + 4 bytes for piece index, but the actual message is 4 bytes for length + 1 byte for message id + 4 bytes for piece index.

    choke: <len=0001><id=0> means 4 bytes for length and 1 byte for message id.

    request: <len=0013><id=6>: 4 bytes for length, 1 byte for id, 4 bytes for piece index, 4 bytes for begin, and 4 bytes for length. ie: 0013 = 1 byte for id + 4 bytes for piece index + 4 bytes for begin + 4 bytes for length, but the actual message is 4 bytes for length + 1 byte for message id + 4 bytes for piece index + 4 bytes for begin + 4 bytes for length.

    I'm currently writing my own torrent client, if you want to check how am I parsing it, you can find it here: https://github.com/Roman15SM/KosTorrentCli/blob/main/Server/TcpCommunicator.cs in the method: MessageProcessor

    Thanks, Roman