C.M.
C.M.

Reputation: 3383

Do I ever need to re-create listening socket?

Suppose I've created a socket, started listen()ing on it and run accept() in a loop to process incoming connections. I.e. smth like this:

s = socket();
bind(s, ...);
listen(s, ...);
loop {
    new_s = accept(s, ...);
    ...                               // do smth with new_s
}

For various reasons accept() can return an error and most of these errors say this particular connection attempt failed, please carry on. Is there any scenario when you have to close the socket and start from scratch (i.e. make new socket + bind + listen) in order to be (eventually) reachable by clients? What error (returned from accept()) tell me that? I.e. should I ever structure my logic like this:

loop {
    loop {
        s = socket();
        bind(s, ...);
        listen(s, ...);
        if !error { break; }
        sleep(1second);               // avoid busy loop
    }

    loop {
        new_s = accept(s, ...);
        if error {
            if error == ??? break;     <--- which error code(s)?
            continue;
        }
        ...                           // do smth with new_s
    }
}

Notes:

Specifically I am looking at ENETDOWN (Linux) and WSAENETDOWN (Winsock2) -- looks like these happen when someone restarts the network (interface). Will my previously created socket continue accepting connections once network is up? I doubt it, but even if it is the case -- how to properly avoid busy accept loop?

Other platforms may have other error codes -- how to write a code that will work on all of them?

Upvotes: 1

Views: 337

Answers (1)

khorton
khorton

Reputation: 79

You don't need to recreate the listening socket if accept() fails on that listener (at least on Windows).

If one called bind on 0.0.0.0:(some port) - then you almost never need to worry about recreating the listening socket.

If one called bind on a specific IP address, and that IP address goes away, then you definitely need to recreate the listening socket (you aren't listening to anything anymore).

Upvotes: 1

Related Questions