setsockopt: Bad file descriptor in C++

6.5k views Asked by At

I have the famous error "address already in use" because I have no check for the bind function.

Here is my code:

memset(&(this->serv_addr), 0, sizeof(this->serv_addr));
this->serv_addr.sin_family = AF_INET;
this->serv_addr.sin_port = htons(port);
this->serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
int yes = 1;
if (setsockopt(sock_fd,SOL_SOCKET,SO_REUSEADDR,&yes,sizeof(int)) == -1) {
    perror("setsockopt");
    exit(1);
}

But running code I got this: setsockopt: Bad file descriptor

The code is right, from the guide Beejnet. But why I got the error? Maybe the position of the code is wrong?

The first the that sock_fd is called is in the function w_socket:

int retv;
retv = socket(AF_INET, SOCK_STREAM, 0);
if(retv == -1)
{
    std::string err_msg(strerror(errno));
    err_msg = "[socket] " + err_msg;
    throw err_msg;
}
else
{
    int reuse_opt = 1;

    setsockopt(this->sock_fd, SOL_SOCKET, SO_REUSEADDR, &reuse_opt, sizeof(int));
    return retv;
}

}

By default there's the sesockopt but no check. I've tried but it doesn't work.

1

There are 1 answers

1
DarkDust On BEST ANSWER

You need to first create the socket via the socket call, like:

sock_fd = socket(PF_INET, SOCK_STREAM, 0);

(and check the return value; see man 2 socket for details)

Only then you may do your setsockopt call. Before the call to socket, your sock_fd variable will contain a random value (or 0) instead of a socket file descriptor.

Edit after updated question:

Your call to setsockopt needs to use retv instead of this->sock_fd as at that point in time, the this->sock_fd variable is not yet containing the result of your call to socket.