The data you send does not contain a terminating null character:
bytes_sent = send(client_socket, string1, strlen(string1), 0);
...because strlen
does not count the terminating null. This isn't exactly the problem in itself, but rather is coupled with the fact that on the receiving side:
char data_received[BUFFER_SIZE];
// ...
bytes_received = recv(ClientSocket, data_received, BUFFER_SIZE, 0);
data_received
is not initialized, and you can receive up to BUFFER_SIZE
bytes. This means that since the data you send is not null-terminated:
If
bytes_received < BUFFER_SIZE
, the rest ofdata_received
may not be initialized so accessing/printing would be undefined behavior. It's actually not 100% clear, as the documentation says:[...] calling recv will return as much data as is currently available—up to the size of the buffer specified [...]
...so it may mean that the rest of the buffer is left untouched.
- If
bytes_received == BUFFER_SIZE
, there is no null-terminator, soprintf
will invoke undefined behavior by trying to print it, since it doesn't know where the string stops and will overrun the array.
The easiest ways to fix these are either to send a null terminator:
bytes_sent = send(client_socket, string1, strlen(string1)+1, 0); // +1 here
bytes_sent = send(client_socket, string1, sizeof(string1), 0); // same as above
...or receive a byte less and put the null terminator on the receiving size:
bytes_received = recv(ClientSocket, data_received, BUFFER_SIZE-1, 0); // -1 here
data_received[bytes_received] = 0;
I'd personally go with the first.