The code below fails connect(2) with errno set to ECONNREFUSED.

The [1] says: “If the connection cannot be established immediately and
O_NONBLOCK is not set for the file descriptor for the socket, connect() shall
block for up to an unspecified timeout interval until the connection is
established.”

Also [1] describes “ECONNREFUSED” error as "The target address was not
listening for connections or refused the connection request."

On some UNIXes connect(2) doesn’t fail, on some (especially BSD) it does.

Code below has only 2 simultaneous connection attempts but backlog is
100000000.

Is this a bug or implementation specific behaviour?

[1] https://pubs.opengroup.org/onlinepubs/9699919799/functions/connect.html


---- cut begin ----

#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>
#include <stdio.h>
#include <err.h>
#include <string.h>
#include <unistd.h>

int main(void)
{
        int s;
        struct sockaddr_un sun;

        size_t i;

        if((s=socket(AF_UNIX, SOCK_STREAM, 0))<0){
                err(1, "socket()");
        }

        memset(&sun, 0, sizeof(sun));
        sun.sun_len=sizeof(sun);
        sun.sun_family=AF_UNIX;
        snprintf(sun.sun_path, sizeof(sun.sun_path)-1,
                "/tmp/socket%d", getpid());

        if(bind(s, (struct sockaddr *)&sun, sizeof(sun))<0){
                err(1, "bind()");
        }

        if(listen(s, 100000000)<0){
                err(1, "listen()");
        }

        for(i=0; i<2; ++i){
                switch(fork()){
                case -1:
                        err(1, "fork()");
                case 0:
                        close(s);

                        while(1){
                                if((s=socket(AF_UNIX, SOCK_STREAM, 0))<0){
                                        err(1, "socket(conn)");
                                }

                                if(connect(s, (struct sockaddr *)&sun,
                                        sizeof(sun))<0){
#if 1
                                        warn("connect()");
#endif
                                }

                                close(s);
                        }

                        break;
                default:
                        break;
                }
        }

        while(1){
                int sc;

                if((sc=accept(s, NULL, NULL))<0){
                        err(1, "accept()");
                }

                close(sc);
        }

        return 0;
}

---- cut end ----

Reply via email to