Search code examples
c++linuxsocketserror-handlingthrow

where is error number of ::accept from socket.h


Here is what I have so far

socklen_t cli_size;
struct sockaddr cli;
int in_sock;

/* event from TCP server socket, new connection */
cli_size = sizeof(cli);
try {
    if ((in_sock  = ::accept(handle,&cli, &cli_size)) < 0) {
        throw in_sock;
        return NULL;
        }
    }
catch(int ex) {
    cout << "Exception Nr. " << ex << endl;
    }

from man page:

On error, -1 is returned, and errno is set appropriately.

Question: I still can't understand where is errno? I need to understand exception


Solution

  • errno is a global integer variable that contains error codes after system calls like accept fails. You might have to include the header file <errno.h> for the variable to be defined.

    In your case, you shouldn't throw the value returned by accept but the value of errno:

    try
    {
        if ((in_sock = accept(...)) == -1)
            throw errno;
        // ...
    }
    catch (int error)
    {
        std::cout << "Error code " << error << " (" << std::strerror(error) << ")\n";
    }
    

    The function std::strerror is declared in the header file <cstring> and returns a string describing the error.

    An important note: The value of errno is only valid if a function returns that it failed. If, in your example, accept succeeds then the value of errno is undefined.