I have a TCP server and client, with an established socket. Let\'s say I have the following case:
SERVER:
char *fn = \"John\";
char *ln = \"Doe\";
char
TCP is stream-oriented, not datagram-oriented. If it was the latter, your stuff would work great. You have the following options:
NUL
byte for terminating each string.For the latter, you would just do send(*socket, buffer, strlen(buffer)+1, 0);
for including the NUL
which is here nevertheless, and the sender would repeatedly recv()
and find a string terminator until it has found 2 strings.
Note that you should take care with strcpy()
: only use it if you are absolutely sure that the string you are writing to is ok.
Your receiver does
bytes = recv(*socket, buffer, sizeof(buffer), 0);
buffer[bytes] = '\0';
That is bad because, if the buffer is full, so bytes == sizeof(buffer)
(which could happen in more complex situations), buffer[bytes] = '\0'
writes beyond the buffer. SO use
bytes = recv(*socket, buffer, sizeof(buffer) - 1, 0);
and you can happily do
buffer[bytes] = '\0';
.