Steven Davis
Steven Davis

Reputation: 63

C Socket Reading TOO MUCH Data

I am making a server that should be able to accept requests from multiple clients. To ensure I am reading large requests properly, I made the below code segment.

Requests come in the form <START_REQUEST>a long message<END_REQUEST>

read(fd, buffer, BUFFER_SIZE);
// Keep Reading If Entire Message Not Recieved
int buffer_len = strlen(buffer);
char *end_tag = &buffer[buffer_len-strlen("<END_REQUEST>")];
while(strcmp(end_tag, "<END_REQUEST>") != 0) {

    char *temp_buffer;
    temp_buffer = malloc(BUFFER_SIZE);

    valread = read(fd, temp_buffer, BUFFER_SIZE);
    strcat(buffer, temp_buffer);

    free(temp_buffer);

    buffer_len = strlen(buffer);
    end_tag = &buffer[buffer_len-strlen("<END_REQUEST>")];
}

However, sometimes (very often) the contents of buffer are something like: <START_REQUEST>a long message<END_REQUEST>somegarbagedataheremaybefromanotherequest? and thus the loop never terminates.

Why might this be happening?

Upvotes: 0

Views: 367

Answers (1)

David Schwartz
David Schwartz

Reputation: 182847

How are you expecting strcat to know how many bytes to append onto the buffer?

valread = read(fd, temp_buffer, BUFFER_SIZE);
strcat(buffer, temp_buffer);

After the call to read, valread holds the number of bytes you read and it's the only thing that holds this information. However, you attempt to append data read onto the existing buffer without using this value -- so there is no possible way strcat could conceivably know how many bytes to append onto the buffer. It's no wonder you append junk that you read before.

Similar problem here:

read(fd, buffer, BUFFER_SIZE);
// Keep Reading If Entire Message Not Recieved
int buffer_len = strlen(buffer);

Here you ignore the return value of read, so you have no way to know how many bytes you read. How are you expecting strlen to figure out how many bytes read put into the buffer?

Upvotes: 2

Related Questions