C++中的BitTorrent对等线路消息



我正在使用C++开发一个torrent客户端。我无法理解与同龄人之间的信息结构。如何使用C++创建一个简单的握手消息,以及如何读取响应?问题是我必须发送的数据的结构,然后我必须读取的结构。我想向种子发送一条握手消息,例如发送BlockBuf。我必须如何创建BlockBuf的内容?问题是我必须用于消息的结构,而不是对等连接……:(

因此BitTorrent握手由以下部分组成,顺序为:

  1. 值为19的字节(后面的字符串的长度)
  2. UTF-8字符串"BitTorrent协议"(与ASCII相同)
  3. 用于标记扩展的八个保留字节
  4. torrent信息散列的20字节
  5. 对等方ID的20个字节

因此,您可以从获得一个足够大的缓冲区开始处理握手消息:

const int handshake_size = 1+19+8+20+20;
char handshake[handshake_size];

提前计算偏移量也有帮助:

const int protocol_name_offset = 1;
const int reserved_offset = protocol_name_offset + 19;
const int info_hash_offset = reserved_offset + 8;
const int peer_id_offset = info_hash_offset + 20;

然后你只需要把它填满。

const char prefix = 19;
const std::string BitTorrent_protocol = "BitTorrent protocol";
handshake[0] = prefix; // length prefix of the string
std::copy(BitTorrent_protocol.begin(), BitTorrent_protocol.end(),
          &handshake[protocol_name_offset]); // protocol name

其余数据依此类推。

然后缓冲区可以直接发送到您将要使用的任何网络API。

要读取回复,您需要提取缓冲区的部分并进行相应的验证:

if(reply[0] != prefix) {
    // fail
}
if(!std::equal(BitTorrent_protocol.begin(), BitTorrent_protocol.end(), &reply[protocol_name_offset]) {
    // fail 
}

等等。

不建议直接从网络读取和写入结构,因为您需要完全控制布局,否则消息格式会不正确。

最新更新