Skip to content
Advertisement

Detect client is disconnected

I have a simple program that listens to a socket. Everything goes fine except when the connection is lost in while(1) cycle. In this case the program falls into read from socket for many times without result. How can I detect a disconnected client in while(1) cycle?

#include <sys/types.h>
#include <sys/socket.h>
#include <netdb.h>
#include <stdio.h>
#include<string.h>


void printHex(char * bts  )
{
    char *s = bts;
    int i=0;
    do
    {
        printf("%02X ", (unsigned char  ) *bts);

    } while (* ++bts !=0);
    printf("%sn",s);

}


int main()
{
    char str[100];
    int listen_fd, comm_fd;

    struct sockaddr_in servaddr;

    listen_fd = socket(AF_INET, SOCK_STREAM, 0);

    bzero( &servaddr, sizeof(servaddr));

    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htons(INADDR_ANY);
    servaddr.sin_port = htons(22000);
    printf("bindingn");

    bind(listen_fd, (struct sockaddr *) &servaddr, sizeof(servaddr));

    printf("listeningn");

    listen(listen_fd, 10);
    printf("acceptingn");

    comm_fd = accept(listen_fd, (struct sockaddr*) NULL, NULL);
    printf("accep donen");

    int cn =0;

    while(1)
    {

        bzero( str, 100);
        printf("will readn");
        int br= read(comm_fd,str,100);
        printf("read donen");

        if (br>0)
        {
            printHex(str);
        }

    }
}

Advertisement

Answer

Change:

    if (br>0)
    {
        printHex(str);
    }

To:

    if (br<=0) break;
    printHex(str);

Also, your code mishandles the case where the first byte is zero. And you can’t avoid this case because TCP does not preserve application message boundaries. You should just pass br to printHex so it will know how many characters to print.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement