gpt4 book ai didi

c++ - 如何解码跟踪器响应中的对等值 (Bittorrent)

转载 作者:行者123 更新时间:2023-11-30 03:47:28 29 4
gpt4 key购买 nike

我正在尝试自己实现 bittorent 协议(protocol),但我在使用 C++ 解码跟踪器响应中的“Peers”值时遇到问题。

根据bittorent协议(protocol)文档:

peers: (binary model) Instead of using the dictionary model described above, the peers value may be a string consisting of multiples of 6 bytes. First 4 bytes are the IP address and last 2 bytes are the port number. All in network (big endian) notation.

如何使用 C++ 解码这些 ip 和端口号?

我已经修改了这段代码,有点不正确:

void DecodePeers(OrderedMap<std::string, int> &map, const char * buffer, int i)
{
int counter = 0;



while (*(buffer + counter) != NULL)
{

//std::vector<TByte> portNum;
short port;

for (int i = counter; i < counter + 4; i++)
{
//*(peerIp + i - counter) = *(buffer + i);
}

counter += 4;

//*(peerIp + 4) = '\0';
char twobytes[2];

twobytes[0] = *(buffer + counter + 0);
twobytes[1] = *(buffer + counter + 1);

unsigned int x;
std::stringstream ss;
ss << std::hex << twobytes[0];
ss >> x;
// output it as a signed type
std::cout << static_cast<int>(x) << std::endl;

port = ((twobytes[1] << 8) | twobytes[0]);
//port = (short) twobytes;
counter += 2;

//std::string str(portNum.begin(), portNum.end());

std::cout << std::endl;

std::cout << port << std::endl ;

char * bbuffer = new char[100];

for (int i = 0; i < 1; i++) {
//unsigned int inte = (unsigned int)str;(
//_itoa_s((int) *str.c_str(), bbuffer, 100, 10);
//sprintf_s(bbuffer, 50, (const char *) "%d", str.c_str());
}

std::cout << std::endl;
//int port = atoi(portNum);
//map.Insert(str, port);
}

}

有人知道如何将此数字转换为数字 - 可读响应吗?

Example of peers value: P^L♠*j.t╤u→πe199711

最佳答案

我试图在你的缓冲区上使用这段代码来解码 bittorrent 协议(protocol)对等体

#include <arpa/inet.h>

int main(int argc, char *argv[])
{
char *buf = "P^L♠*j.t╤u→πe199711";
int chunks = strlen(buf) / 6 ;
int offset = 0;
unsigned char *ip;
unsigned short *port;
int recsDone = 0;
while (recsDone++ <= chunks){
ip = (unsigned char *) buf+offset;
port = (unsigned short *) buf+offset+4;
printf("%s - %d\n",inet_ntoa(*(in_addr*)ip),ntohs(*port));
offset+=6;
}
}

我得到这个作为输出:

80.94.76.226 - 1189242.106.46.116 - 12601

如果它有效,请告诉我们。

关于c++ - 如何解码跟踪器响应中的对等值 (Bittorrent),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33675913/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com