UtPex
BEP-11 "Peer Exchange (PEX)" (ut_pex). This is the pure message codec, ported from libtorrent's ut_pex.cpp (src/ut_pex.cpp, ut_pex_plugin::tick builds the message and ut_pex_peer_plugin::on_extended parses it).
PEX lets connected peers gossip the addresses of other peers, so a swarm can grow without everyone hammering the tracker. A PEX message is the bencoded payload of a BEP-10 extended message (id 20), carried under the extension id the remote peer advertised for ut_pex.
Wire format
A single bencode dict with up to six string keys:
| key | contents |
|---|---|
added | compact IPv4 peers, 6 bytes each: 4-byte IP + 2-byte port |
added.f | one PexFlags byte per peer in added, same order |
dropped | compact IPv4 peers that left since the last message |
added6 | compact IPv6 peers, 18 bytes each: 16-byte IP + 2-byte port |
added6.f | one flags byte per peer in added6 |
dropped6 | compact IPv6 peers that left |
All integers (IPs and ports) are network byte order (big-endian); a port like 6881 is the two bytes 0x1a 0xe1. There are no flags for dropped peers.
libtorrent only parses added/added.f when their lengths agree (added.f.length == added.length / 6); a mismatch means the whole added list is ignored. parse reproduces that. The internal pex_lt_v2 flag (bit 0x10) is masked off on receive, because it must not be trusted from the wire. See PexFlags.RECEIVE_MASK.
This class is the codec only; the once-a-minute scheduling, the dedup against previously-sent peers, and the add_peer side effects live in the peer-plugin layer.
Types
The result of a Builder.tick: the Message to send plus the set of (ip,port) keys that were sent as added, so the caller can record what the remote now knows. Builder already tracks this internally, but exposing it lets the session log or audit.
A fully parsed PEX message: the four logical lists libtorrent reads out of the dict. IPv4 and IPv6 are merged here for convenience, because each PexPeer knows its own family via PexPeer.isV4. encode still writes them into the correct added and added6 keys.
Properties
Bytes per compact IPv4 peer entry: 4-byte address + 2-byte port.
Bytes per compact IPv6 peer entry: 16-byte address + 2-byte port.
The default cap on how many added peers a single PEX message carries, so a packet stays small. libtorrent uses max_peer_entries = 100 (ut_pex.cpp:61); this port caps at 50 per the session policy. dropped peers are not counted against this limit. Only newly-added ones count, matching if (num_added >= max_peer_entries) break; in ut_pex_plugin::tick.
Functions
Parse a PEX message payload (the bencoded body of the extended message, without the wire framing).