Reputation: 21
I am trying to write a torrent client in C , so far I have written Bencode Parser, But I am stuck on networking part.
According to specification Specification after the initial handshake and sending the INTERESTED MESSAGE, we can request for piece.
I am able to send and receive the handhshake message , send the INTERESTED MESSAGE , but not able to get any pieces.
Here is the code I am using to follow the process
The bt_msg_t is structure is taken from Swathmore Lab Assignment Guide(PgNo.5)
// Interested Message
bt_msg_t Sendmsg;
Sendmsg.length = sizeof(Sendmsg.bt_type);
Sendmsg.bt_type = BT_INTERSTED;
int SendmsgSize = sizeof(Sendmsg.bt_type) + sizeof(Sendmsg.length);
assert(sendData(sockfd, (char*)&Sendmsg,SendmsgSize ) == 1);
//Piece-Request
bt_msg_t Sendmsg;
Sendmsg.bt_type = BT_REQUEST;
Sendmsg.payload.request.begin = 0;
Sendmsg.payload.request.index = 0;
Sendmsg.payload.request.length = 4;
Sendmsg.length = sizeof(Sendmsg.bt_type)+sizeof(Sendmsg.payload);
assert(sendData(sockfd, (char*)&Sendmsg, sizeof(Sendmsg)) == 1);
//SendData is a wrapper over send() tcp function
//Fetching the Piece
do {
receiveData(sockfd, 8, buffer, 1);//recvData() is a wrapper over receiveData
memcpy(&Recvmsg, buffer, sizeof(Sendmsg));
memset(buffer, 0, sizeof(buffer));
} while (Recvmsg.bt_type!=BT_PIECE);
//
The code gets stuck on Fetching the piece part and the peer is not responding with the piece requested, is it peer fault or there is something wrong with my code ?
Here is my self created torrent file that I am using as reference TorrentFile
sendData() and receiveData() code snippet that I am using.
int sendData(int sockfd,char data[],ssize_t len)
{
ssize_t tot_sent = 0;
// ssize_t len = 68;
while (tot_sent < len) {
ssize_t sent = send(sockfd, data, len - tot_sent, 0);
if (sent < 0)
{
std::cout << "No data sent\n";
return -1;
}
std::cout << "Sent:" << sent << '\n';
tot_sent += sent;
handshake += sent;
}
return 1;
}
int receiveData(int sockfd, ssize_t len, char* buff, int flag)
{
unsigned tot_recv = 0;
ssize_t nb=0;
// char buff[len];
if (len == 0) {
std::cout << "No data available" << '\n';
return -1;
}
do {
assert(len - tot_recv > 0);
nb = recv(sockfd, buff + tot_recv, len - tot_recv, 0);
if (nb < 0) {
std::cout << "No data received" << '\n';
return -1;
}
std::cout << "Received in chunks :" << nb << "\n";
tot_recv += nb;
} while (nb > 0 && tot_recv < len);
if (tot_recv == len) {
std::cout << "Received All" << '\n';
return 1;
// return;
}
return -1;
}
Upvotes: 1
Views: 84