user1313410
user1313410

Reputation: 27

TCP Client Server Program

I am doing a programming assignment, and I have pretty much figured out the missing information from the skeleton code given, However, For the life of me I cannot figure out how to actually print the message recieved from the client! int recv (int socket, char *buff, int buff_len,int flags) I am using this filled in with the proper information, hopefully, to receive a message from the client. However I have no idea how to actually print it on the server!

I tried cout << buff; but that just seems to break the program. I should also note I am doing this assignment in Putty.

Upvotes: 0

Views: 122

Answers (1)

Jeremy Friesner
Jeremy Friesner

Reputation: 73041

You didn't show the actual code you are using to receive and print the message, but the most likely reason that cout << buff; is misbehaving is because it expects its argument to point to a 0-terminated char-array, and recv() does not 0-terminate the data it writes into your array. Because of that, the printing logic in the << operator will iterate past the end of the array looking for a 0-terminator-byte, and invoke undefined behavior.

The simple way to avoid that problem is to add a 0-terminator byte yourself, like this:

 char buff[512];
 int numBytesReceived = recv(sockFD, buff, sizeof(buff)-1, 0);
 if (numBytesReceived > 0)
 {
    buff[numBytesReceived] = '\0';  // place 0-terminator byte at end of received data
    cout << buff << endl;  // now it's safe to print
 }
 else if (numBytesReceived == 0) cout << "connection closed!" << endl;
 else perror("recv");

Upvotes: 1

Related Questions