Test on Linux (particularly: Ubuntu 20.04 LTS, kernel 5.4.0): in Python:
from socket import *
s1 = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
s1.bind(('', 11001))
s2 = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
s2.bind(('', 11001)) ## Here it fails: EADDRINUSE
So, at the moment s1 is bound, the port use is already registered somewhere in system.
But, unless I call listen()
or connect()
on the socket, it won't be shown in any registry I could find. /proc/net/tcp
doesn't list it, nor
netstat
nor ss
. lsof
lists it but without the port:
python3 28296 netch 5u sock 0,9 0t0 4311999 protocol: TCP
python3 28296 netch 6u sock 0,9 0t0 4312006 protocol: TCP
Only when I call listen() on the socket, it appears in visible lists:
$ ss -at | grep 11001
LISTEN 0 128 0.0.0.0:11001 0.0.0.0:*
TCP here is not a single case (originally I've faced it with SCTP, in the same manner).
To compare with, FreeBSD (tested 12.3) immediately lists the socket (checked using sockstat
):
$ sockstat -P tcp -p 11001
USER COMMAND PID FD PROTO LOCAL ADDRESS FOREIGN ADDRESS
netch python3.8 797 4 tcp4 *:11001 *:*
Is there a tool to list presence of such sockets? Could it be done without iteration of all processes? Why the standard tools (like netstat, ss) ignore the issue?
Or maybe this: https://unix.stackexchange.com/a/9284/258734
– Mikolaj Buchwald May 24 '22 at 22:35lsof
iterates all processes. But the principal fact is that they are still candidates and there is no information to select a proper one without killing all them in line. – Netch May 30 '22 at 06:48