Adriano
Adriano

Reputation: 389

C server weird behavior

So, I have this piece of code, which will just read the message from the client and reply with a "yup"

while(strcmp(buffer, "QUIT") != 0){ 
    bzero(buffer, 255); //cleans the read buffer

    /*this reads the aux (request) from the client*/
    recv(newsockfd, buffer, 255, 0);

    if(strlen(buffer))
        printf("Thread %d: %s\n", thread_no, buffer);
    fflush(stdout);

    write(newsockfd, "yup\n", 4);
}

The problem is that at the very first reading everything goes ok, but all other readings are messed up, if I send the message "guitar", for example, it gets the 'g', loops and then it gets the "uitar", sending aother "yup".

I have no clue what's happening.

Upvotes: 0

Views: 71

Answers (3)

selbie
selbie

Reputation: 104579

Three other bugs in the code snippit above.

1) Not checking the return value from recv(). The socket could have been closed gracefully (return value == 0), suffered an error (return value == -1), etc... More importantly, there's not to suggest that you will receive all 4 bytes of the "QUIT" message that was sent by a remote send call. You may only receive "Q".

2) If recv() were to receive 255 characters (none of which being a null char), then the subsequent strlen() will read into invalid memory and possibly crash.

3) Not checking the return value of the write call.

Upvotes: 0

glglgl
glglgl

Reputation: 91129

recv() reads as many data as are available currently. You should read until you hit EOF, an error or a newline. Only if you have that newline, you have a complete line which you then compare with "QUIT", and which youi acknowledge with "Yup."

Upvotes: 0

James M
James M

Reputation: 16728

Long story short: TCP isn't a message orientated protocol, it's a stream orientated protocol. Messages might be fragmented or merged together, and your application has to deal with that (the only guarantee is that you'll receive the data in the same order you sent it in).

Upvotes: 6

Related Questions