AndroidDev
AndroidDev

Reputation: 21237

send() commands in a loop just keep appending data

I have a TCP send() command inside of a loop. I am noticing that each message that I send just appends to the end of the previously sent message. I don't know why. I've tried both memset and bzero to clear my char *, but I get the same result. Anyone see why?

char *lsp = malloc(128);

for (i=0; i<3; i++) {

    memset (lsp, 0, 128); // also tried bzero here
    lsp_builder(lsp, this_router->label, routing_table, num_hosts-1, ++seq);
    fprintf (logfd, "\tCreated the following lsp: %s\n\n", lsp); //<--looks great

    for (i=0; i<6; i++) {
        send (sockfd[i], lsp, strlen(lsp), 0);
    }
}

Then, on the receiving end, I have this code:

char incoming_lsp[128];
bzero(incoming_lsp, sizeof(incoming_lsp));
recv(newfd[i], &incoming_lsp, sizeof(incoming_lsp), 0);

// this is where I can see the data being appended
fprintf(logfd, "\tReceived: %s\n", incoming_lsp); 

Upvotes: 0

Views: 71

Answers (1)

simonc
simonc

Reputation: 42175

If you want to send individual strings, you need to include their null terminators in the messages

send (sockfd[i], lsp, strlen(lsp)+1, 0);
//                               ^^

Note also that a single call to recv is not guaranteed to return a single, full buffer from send. You need to check the return value from recv to see how many bytes it returns, calling it repeatedly in a loop until you read your target message length or find your target message terminator.

Upvotes: 2

Related Questions