Sagar
Sagar

Reputation: 9503

Accept fails on invalid argument, followed by bad file descriptor

We have a server that has been perfectly functional for the past few months. However, out of the blue - yesterday - the server failed to accept a connection with "invalid argument", and subsequently with "bad file descriptor".

Every site/suggestion I've checked says I should have a listen() after bind() and before accept(). I do, and I'm also checking for errors on listen().

I am correctly passing the size of the client sockaddr_in, to accept(), and it is initialised to the size of the client sockaddr_in variable.

I have also checked to make sure I am using AF_INET along with sockaddr_in (as opposed to AF_UNIX or sockaddr_un.

Any ideas?

Basic pseudocode:

struct sockaddr_in server;
struct sockaddr_in client;
socklen_t client_size;

if ((mysock = socket(AF_INET, SOCK_STREAM, 0)) < 0) exit;

memset(&server, 0, sizeof(server));
// Set socket options
server.sin_family = AF_INET;
server.sin_addr.s_addr = INADDR_ANY;
server.sin_port = 8000;

if (bind(mysock, (struct sockaddr *) &server, sizeof(server)) < 0) exit;

if (listen(mysock, 100) < 0) exit;

while (1)
{
    clientsock = accept(mysock, (struct sockaddr *) &client, &client_size);
    if (clientsock == -1)
        printf("Accept failed() - %s\n", strerr(errno));
    else
        //do server stuff here
}

It was working fine one minute, and the next it started printing a ton of "Accept failed()" errors, the first one being Invalid Argument and the rest were Bad file descriptor.

Nothing changed on that server (that we know of).

Note: clientsock and mysock are initialised. I just have not shown it here. If you see issues with parentheses, it's a copy-paste issue, not a code issue. Like I said, the server has been fine for a long time.

Upvotes: 0

Views: 577

Answers (1)

alk
alk

Reputation: 70931

As the <-operator binds tighter then the =-operator this

if (mysock = socket(AF_INET, SOCKSTREAM, 0) < 0) exit;

shall look like this

if ((mysock = socket(AF_INET, SOCKSTREAM, 0)) < 0) 
  exit;

or even better (as more obvious and though more safe) like this:

mysock = socket(AF_INET, SOCKSTREAM, 0);
if (0 > mysock)
{
  exit;
}

Upvotes: 2

Related Questions