I am writing a bittorrent client in C++. When my program contacts the tracker using the info provided in the .torrent file, it sometimes doesn’t send enough bytes back. The response, as defined by the bittorrent protocol specification ( http://wiki.theory.org/BitTorrentSpecification#Tracker_Response ), should be a bencoded dictionary, which means it should start with a ‘d’ and end with an ‘e’. Here is the code I am using to receive and store the tracker response:
int iResult;
char recvBuf[512];
int recvBuflen = 512;
string response;
//Receive response from tracker
do{
iResult = recv(ConnectSocket, recvBuf, recvBuflen, 0);
if(iResult > 0){
printf(" - Bytes Received: %d\n", iResult);
response.append(recvBuf, 0, iResult);
} else if(iResult == 0){
printf(" - Connection Closed\n");
} else {
working = false;
printf(" - Failed: %d\n", WSAGetLastError());
return 1;
}
} while(iResult > 0);
and here is what is in the response string when I look in the Watch feature in Visual Studio (after the connection has been closed):
HTTP/1.1 200 OK
Content-Type: text/plain
Content-Length: 399
d8:completei213e10:downloadedi139e10:incompletei17e8:intervali1970e12:min intervali985e5:peers300:Yšqö*^ýåȵµcü*—®€Éýò6¸VÉ_0ºàÉQªUºÉÆ’÷ºÉQñ½ÎâV¬ãß¾Ã,Ië{¾£é´ÈÕ½ÇMÈn½ÖQÖ¼1¼K]»k„Îź×
Pź|Á¶X¼ºMä¸B”‹žÆ²”Œ2œ±ªÈj°4Ìú·¯«ö’î¯+r€c¯‰“r¦Î´Ã7Íœ”5ÄcÿICÈ|´””ø3yÛæÜâÕsø¿³©nŸ¤u±ýmÿ‡µmš8äScûÜ8ý–_÷
The 300 after peers means that the data following 300: should be 300 bytes long. I put the data in a character counter and there was only 212 characters (bytes) which leads me to believe that the response was cut off. It also does not end in an e.
This only seems to happen when there is binary data involved. Is it possible that the binary data contained the binary for the ‘\0’ character which caused it to be cut off prematurely? How would I fix that? Thank you 🙂
It could simply be that the debugger displays the string until up to the first null char. You could consider using a
vector<unsigned char>instead since you are dealing with raw bytes here.