Skip to content
Peer Messages
step 1/5

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:

IDNamePayload
0choke-
1unchoke-
2interested-
3not interested-
4have4 bytes: piece index
5bitfieldbytes: 1 bit per piece (have=1)
6request12 bytes: index + offset + length (each 4 bytes)
7piece4 byte index + 4 byte offset + N bytes block
8cancelsame as request
9port2 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…