Search code examples
clinuxsocketsunix-socket

How to check if other end of a socket has been accepted?


I have a client/server set up and I want my client to know if the server has accepted the connection. Otherwise my client has no clue it's still waiting to be accepted. I can't rely on further communication (protocol specification) to verify this. So for example sending a "Good to go" string from the server to the client is not an option. Is there a flag or something that I can check to see if the server is indeed receiving? Some example code follows:

/* Client */
...
getaddrinfo(ip, port, &hints, &servinfo);
connect(sockfd, info->ai_addr, info->ai_addrlen);

if (info == NULL) {
    printf("connection failure\n");
    exit(1);
}

inet_ntop(info->ai_family, get_in_addr((struct sockaddr *)info->ai_addr), ipstring, sizeof(ipstring));
printf("Connected to %s!\n", ipstring);
...

/* Server */
...
pause(); /* If don't accept the connection, how to make the client know? */ 
new_fd = accept(sockfd, (struct sockaddr *)&cli_addr, &addr_size);
...

Solution

  • Because of backlog, server can send SYN-ACK before accept call. So Client call connect() can return before server calls accept().

    As you say: "Good to go" message from the server is not option. How about: "echo" request from client. So Server will respond after accept.

    If any extra traffic in the TCP stream is not an option. Can you use ancillary data?