How to detect unconnected AF_UNIX sockets

jb jb.1234abcd at
Mon Sep 10 12:41:37 UTC 2012

Sam Varshavchik <mrsam <at>> writes:

> I'm porting existing code from Linux where a connect() to an AF_UNIX socket  
> that exists, but does not have a listener, fails with ECONNREFUSED. This is  
> quite agreeable with the comparable scenario in AF_INET, with a connection  
> attempt to a port without a listener on it. So the same code handles both  
> situations, immediately reporting an error, and without caring much about  
> the type of the socket.
> But on FreeBSD, according to truss, it seems that a connect() to an AF_UNIX  
> socket without a listener still succeeds. A subsequent write() also  
> succeeds, and read() blocks.
> The fall-out is quite unfortunate, and I was hoping for a way to detect that  
> my allegedly connected socket is lying to me, and it's not really connected  
> to anything. How would I go about doing that? I tried using the  
> LOCAL_CONNWAIT option as documented in unix(4), but that does not appear to  
> make any difference, in this situation.

It seems to work here:
$ uname -a
... FreeBSD 9.1-RC1 #0 ...

$ ls -al /tmp/server 
srwxr-xr-x  1 jb  wheel  0 Sep 10 14:22 /tmp/server
$ ps auxww |grep -i server-af_unix
$ ./client-af_unix 
client af_unix: connect() errno = 61
connect() failed: No such file or directory
$ grep 61 /usr/include/errno.h
#define	ECONNREFUSED	61		/* Connection refused */

Client code:
      rc = connect(sd, (struct sockaddr *)&serveraddr, SUN_LEN(&serveraddr));
      if (rc < 0)
         printf("client af_unix: connect() errno = %d\n", errno);
         perror("connect() failed");


More information about the freebsd-questions mailing list