2

I'm playing around with Linux domain sockets and now I came to the issue about understanding backlog. Here is the server side code:

const char *const hostname = "/tmp/test_local_addr";

int sock_fd = socket(AF_LOCAL, SOCK_STREAM, 0);

struct sockaddr_un server_address;
memset(&server_address, '\0', sizeof(struct sockaddr_un));
server_address.sun_family = AF_LOCAL;
strncpy(server_address.sun_path, hostname, hostname_len + 1);
const socklen_t addrlen = offsetof(struct sockaddr_un, sun_path) + hostname_len + 1;

bind(sock_fd, (struct sockaddr*) &server_address, addrlen);

int listen_result = listen(sock_fd, 0);

I set the backlog size to 0 in the listen and do not call accept method so I expected that any client would receive Connection refused when trying to connect. But when I ran strace nc -U /tmp/test_local_addr from two separate terminals I have the first one prints

connect(3, {sa_family=AF_UNIX, sun_path="/tmp/test_local_addr"}, 110) = 0
poll([{fd=0, events=POLLIN}, {fd=3, events=0}, {fd=3, events=POLLIN}, {fd=1, events=0}], 4, -1

and the second

--- SIGWINCH {si_signo=SIGWINCH, si_code=SI_KERNEL} ---
connect(3, {sa_family=AF_UNIX, sun_path="/tmp/test_local_addr"}, 110

The behavior is not really clear to me. I expected they both immediately terminates with Connection refused. But the

read(-1, 0x7fffc0db3740, 16384)         = -1 EBADF (Bad file descriptor)

happens in both clients only when I terminate the server.

Some Name
  • 8,555
  • 5
  • 27
  • 77
  • 1
    If you don't want to accept connections don't bind to the socket in the first place. `listen(0)` makes no sense which means the `0` gets likely internally replaced with some sane value. And not doing `accept` does not matter since `accept` cares about getting already established connections from the kernel to the user space and not about starting the TCP handshake as you might assume. – Steffen Ullrich Dec 25 '18 at 08:37
  • @SteffenUllrich I tried to set `backlog` to 1 and now the two clients can `connect(3, {sa_family=AF_UNIX, sun_path="/tmp/test_local_addr"}, 110) = 0`, but the third one is blocked `connect(3, {sa_family=AF_UNIX, sun_path="/tmp/test_local_addr"}, 110` – Some Name Dec 25 '18 at 08:46
  • 1
    see [listen() ignores the backlog argument?](https://stackoverflow.com/questions/5111040/listen-ignores-the-backlog-argument). – Steffen Ullrich Dec 25 '18 at 10:34
  • @SteffenUllrich Thanks. It means it can never be `null` and just an advice... like you said. – Some Name Dec 25 '18 at 10:38

0 Answers0