###Should not assume null termination###
Should not assume null termination
This code in the server assumes that the client will send null terminated data:
//Receive a message from client while( (read_size = recv(sock , client_message , 2000 , 0)) > 0 ) { //Send the message back to client write(sock , client_message , strlen(client_message)); printf("%s\n",client_message); }
There are several problems with that:
- The client could not send null terminated data.
- The client could send a string longer than 2000 bytes, which would look unterminated.
- Even if the client were well behaved, sockets don't necessarily send/receive all of their data in one chunk. So the client might send a 1000 byte string but your
recv()call might only read 500 bytes (with no null termination).
To fix this,you should use read_size to terminate the string yourself (and make your buffer bigger by one character). Or pick a new message protocol that sends a length followed by a string of that length, so you can better determine where each message ends.