Reading — step 1 of 5
Read
~1 min readPeer Wire Protocol
Peer Messages
After handshake, peers exchange typed messages with this frame:
4 bytes: length prefix (big-endian)
1 byte: message ID (only present if length > 0)
N bytes: payload
A length of 0 is a keep-alive (no ID, no payload). Sent every 2 minutes.
Message types:
| ID | Name | Payload |
|---|---|---|
| 0 | choke | - |
| 1 | unchoke | - |
| 2 | interested | - |
| 3 | not interested | - |
| 4 | have | 4 bytes: piece index |
| 5 | bitfield | bytes: 1 bit per piece (have=1) |
| 6 | request | 12 bytes: index + offset + length (each 4 bytes) |
| 7 | piece | 4 byte index + 4 byte offset + N bytes block |
| 8 | cancel | same as request |
| 9 | port | 2 bytes: DHT port |
Pieces are typically 256 KB to 4 MB. Requested in 16 KB blocks (per BEP 3 convention). So a 1 MB piece = 64 sequential request messages, and we accumulate 64 piece responses.
The request pipeline: send multiple requests before waiting for responses to keep the TCP pipe full. Typical: 5-20 outstanding requests at a time.
For this lesson: encode/decode message frames.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…