Search code examples
csocketstcperror-handling

Handling send e recv errors in C


I'm new in C language and I'm writing a TCP server

// create a socket, bind and listen
while(1) {
 accept:
 int conn_sock = accept(...);
 // here some recv and send calls
}

I want to prevent server shutdown if ECONNRESET or EINTR occurred. If one of this errors occur while sending or receiving data I want to go to accept (want to go to accept label if accept() fails for some reason as well).

If I don't catch these errors my server stops to work if a client close the connection.

How can I catch these errors and go back to accept to establish a connection with another client?


Solution

  • On error accept() returns -1. The error's reason then can be read from errno.

    One possible approach so would be:

      int errno_accept;
      while (1)
      {
        errno_accept = 0;
        int accepted_socket = accept(...);
        if (-1 == accepted_socket)
        {
          errno_accept = errno;
          switch(errno_accept)
          {
            case EINTR:
            case ECONNRESET: /* POSIX does *not* define this value to be set 
                           by a failed call to accept(), so this case is useless. */
    
            default:
              /* Catch unhandled values for errno here. */
    
              break; /* Treat them as fatal. */
    
            ...
      } /* while (1) */
    
      if (0 != errno_accept)
      {
        /* Handle fatal error(s) here. */
      }