Can we bind a Unix domain socket to any random existing file ? If no, how do you recognize a file that is used by a socket ?
1 Answers
Can we bind a Unix domain socket to any random existing file
No. The file should not exist, or bind(2)
will fail with EADDRINUSE
. bind(2)
will create a new file with the path given in .sun_path
.
If no, how do you recognize a file that is used by a socket?
lsof
may help. Up to a point.
Or ss
:
$ nc -Ul foo &
[3] 9268
$ ls -i ./foo
1179674 ./foo
$ ss -elx | grep -w 1179674
u_str LISTEN 0 5 foo 618789 * 0 <-> ino:1179674 dev:0/2072 peers:
(the ss
output above was manually trimmed of white spaces)
The -l
option will direct ss
to select only listening sockets, the -x
option only Unix sockets, and the -e
option to print extended info, as the inode number I've used to match the file.
Both ss
and lsof
will only see the sockets from the current network namespace; but two unix sockets from different network namespaces cannot be bound to the same file.
You may want to check if the device numbers match too; but you should proceed carefully, because the sock_diag(7)
(as used by ss
) will return it in the format used internally by the kernel (MMMm mmmm
), but the buggy ss
will treat as if it were in the mmmM MMmm
userland format; the device number in the example above is not 0/2072
, but 8/24
(/dev/sdb8
) ;-)
ss
been fixed yet? – 炸鱼薯条德里克 Dec 15 '19 at 05:01unshare -Un nc -Ul /tmp/sock
in a terminal, andss -xl | grep /tmp/sock
orlsof /tmp/sock
in another. Of course, you can connect to a unix socket from another namespace, if you can access the file it's bound to. 2. fixing it now will break all the scripts which use workarounds for it. – Dec 15 '19 at 05:20ls -l file
tells you whether the file is a Unix socket. The very first character will be ans
in that case. Very simple. – Alexis Wilke Jul 20 '21 at 17:23ls -l file
does NOT tell you if a socket file is actually in use -- ie if any process is actually listening on, bound to or connected to it. Reliably determining that is not simple at all, for all the reasons already mentioned in this and the linked answer. – Jul 22 '21 at 04:51