Q:

recv() does not get value from network

I Have a typical client server C socket program. 
SERVER:
            if(ndp.cmd == 11)
            {   
                //ack1 = 0;
                puts("Query Command for Light 2");
                pthread_mutex_lock(&lock);  
                // ..Some critical stuff
                pthread_mutex_unlock(&lock);    
                printf("ID: %d, Level: %d\n", new.address, new.level);
                ack1 = new.level; //This result is showing correct on server
                ack1 = htonl(ack1);
                send(client_sock, &ack1, sizeof(ack1), 0);              
            }

CLIENT:
    printf("Query Actual level Light2\n");
    dp.id = 2;dp.cmd = 11; dp.active = 0; dp.level = 0; dp.group = 0; 
    if( send(sock , &dp , sizeof(dp) , 0) < 0) { puts("Send failed"); }
    sleep(1);
    ret = recv(sock , &level1 , sizeof(level1) , 0);
    printf("Number of bytes received: %d\n", ret); //Always gives 4
    fflush(stdout);
    printf("Light level %x\n", ntohl(level1) ); //This prints 0 (incorrect)
    fflush(stdout);
    sleep(5);

    printf("Query Actual level Light2\n");
    dp.id = 2;dp.cmd = 11; dp.active = 0; dp.level = 0; dp.group = 0; 
    if( send(sock , &dp , sizeof(dp) , 0) < 0) { puts("Send failed"); }
    sleep(1);
    ret = recv(sock , &level2 , sizeof(level2) , 0);
    printf("Number of bytes received: %d\n", ret); // Always gives 4
    fflush(stdout);
    printf("Light level %x\n", ntohl(level2) ); //This prints correct value
    fflush(stdout);
    close(sock);

Expected output:
Light level 32 (hex value for 50);
Light level 32

Actual output:
Light level 0
Light level 32

So the problem is on same requests, 1st send from server is not received by client, but next recv() gives correct value.
Why is the data from 1st recv() getting lost, is it getting buffered and maybe I am getting the previous value in 2nd recv() ?
Please help.

A:

Your assumption is not wrong. It may be buffered. Also note that when the receiver reads data faster than the sender does send it, some recv calls may read no data since the sender did not send any data yet. That could be the cause of what you're describing.
UPDATE: If you plan to always send/receive the same amount of data, for example a 20-byte packet containing what you defined as a command, then you can wrap your send and recv in a loop. This loop will write (or read) a single command at a time. You cannot assume a call to send or recv will succeed, so you MUST check for errors as @Joachim mentioned in comments. Another thing to note is that recv MAY read less bytes than the specified, so you may have to read multiple times in order to receive the complete command. The same applies to send.

