简体   繁体   中英

Recv call get empty data

I'm learning to work with sockets in c. Here is my code:

void work_with_client(int client_sock){
    char buff[10] = {0};

    while(1){
            kv_log_message("\tWork with client\n");
            int is_received = recv(client_sock, buff, 10, 0); 
            if(is_received < 0){ 
                    perror("Received failed");
            } else {
                    printf("RESPONSE: %s\n", buff);
            }   
            printf("RESPONSE %d\n", is_received);

            sleep(1);
    }   
}

When I connect through telnet to this server and immediately disconnect, server print this lines:

    Work with client
RESPONSE: 
RESPONSE 10
    Work with client
RESPONSE: 
RESPONSE 10
    Work with client
RESPONSE: 
RESPONSE 10
    Work with client
RESPONSE: 
RESPONSE 10
    Work with client
RESPONSE: 
RESPONSE 1
    Work with client
RESPONSE: 
RESPONSE 0
    Work with client

And I don't get why first 4 recv calls get full size of buffer data (I don't write anything to the socket from client perspective). Any suggestions? PS Run on Mac OS X Yosemite

UPDATE: i test my program on Linux, and recv call always return 0 in my case, so probably the problem in telnet on Mac OS X

When recv() returned 0 this indicates the other side shut down the connection.

From man recv :

RETURN VALUE

[...] The return value will be 0 when the peer has performed an orderly shutdown.

You then might like to exit the while() loop.


Update:

Also the code might invoke undefined behaviour by passing a non 0 -terminated "string" to printf() .

To fix this read one char less to buff then it's size and add the 0 -terminator.

    while (1)
    {
        ssize_t is_received = recv(client_sock, buff, sizeof buff - 1, 0); 
        if (is_received < 0){ 
                perror("Received failed");
                break;
        } else if (is_received == 0) {
                printf("%s\n", "peer shutdown");
                break;
        }

        buff[is_received] = '\0';
        printf("RESPONSE: %s\n", buff);
   }   

Ok i get it, telnet on Mac OS X (Yosemite) send some data if you just close terminal without proper closing connection through telnet itself (ie put escape character and quit command).

Honestly I don't know is it bug or some kind of debug behaviour.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM