C: how to clear out buffer from a read() on a socket

buffer, c, sockets, string

Solution

It seems to me that in your code you delete the received data before printing it - then you pass a string to `printf` that is basically empty, and I'm not sure what `printf` does with that (since it is the formatting string that is empty).

Try this:

int nread;
while((nread = read(client_sock_desc, receive, sizeof(receive)-1)) > 0) {
        receive[nread]='\0';    // explicit null termination: updated based on comments
        printf("%s\n",receive); // print the current receive buffer with a newline
        fflush(stdout);         // make sure everything makes it to the output
        receive[0]='\0';        // clear the buffer : I am 99% sure this is not needed now
    }

Problem

I am trying to receive data from a server, and it works fine for the first time, but as read() keeps looping it will also store the old values it previously read. Here is what i have so far. ``` char receive[50]; if((he = gethostbyname(servername)) == NULL ) { perror(strcat("Cannot find server named:", servername)); exit(0); } he = gethostbyname("localhost"); localIP = inet_ntoa(*(struct in_addr *)*he->h_addr_list); client_sock_desc = socket(AF_INET, SOCK_STREAM, 0); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr(localIP); server_addr.sin_port = htons(serverport); len = sizeof(server_addr); if(connect(client_sock_desc, (struct sockaddr *)&server_addr,len) == -1) { perror("Client failed to connect"); exit(0); } strcpy(buf, "CLIENT/REQUEST\n"); send(client_sock_desc, buf, strlen(buf), 0); //send actual function request //put a space before \n char to make it easier for the server for(i = 0; i < sizeof(wholeRequest); i++) { if(wholeRequest[i] == '\n') { wholeRequest[i] = ' '; wholeRequest[i+1] = '\n'; break; } } while(read(client_sock_desc, receive, sizeof(receive)) > 0) { strcpy(receive, ""); //attempt to erase all old values printf(receive); fflush(stdout); } close(client_sock_desc); ``` When the server sends data once and closes the socket, it works perfectly. But then I have the client open the socket again, send data to the server, and the server will once again send data to the client and close the socket. The client will again try to read the data the server sent, but this time it fills receive with both the new information and part of the old information

Original source