Lição 04 · Unit 2 · Networking for a Backend Engineer & Application Support

Who's Listening? Sockets and `ss`

Rung 2 of the ladder asks "is the port reachable?" — but before you debug a connection you need to see the connections a box already has. One command shows them all: ss. Start a server and look.

python3 -m http.server 8000 &      # a listener on port 8000
ss -tlnp                            # t=TCP  l=listening  n=numeric  p=process
State   Recv-Q  Send-Q  Local Address:Port  Peer Address:Port  Process
LISTEN  0       128           0.0.0.0:8000       0.0.0.0:*      users:(("python3",pid=812,fd=3))

That one line is a listening socket: a process (python3) parked on a port (8000), waiting. 0.0.0.0 means "on every interface"; Peer is * because nobody has connected yet.

The 4-tuple

A curl to a local server is over in well under a millisecond — far too fast to catch with ss (run curl … & then ss and you'll see nothing, because the connection already closed). So hold one open by hand: bash can open a raw TCP socket on a file descriptor and just sit on it.

exec 3<>/dev/tcp/127.0.0.1/8000    # open a connection on fd 3 and HOLD it
ss -tnp | grep 8000                # now it's alive and there to see
State  Recv-Q  Send-Q  Local Address:Port  Peer Address:Port  Process
ESTAB  0       0         127.0.0.1:8000      127.0.0.1:51834   users:(("python3",...))
ESTAB  0       0         127.0.0.1:51834     127.0.0.1:8000    users:(("bash",...))

Release it with exec 3>&- when you're done looking.

Every TCP connection is identified by exactly four values — the 4-tuple:

Local Address:Port
your side of the connection.
Peer Address:Port
the other side of the connection.
The tuple
(local IP, local port, peer IP, peer port) — unique for every connection on the box.

This is why one server port serves thousands of clients at once: the server side is always :8000, but each client arrives with a different (IP, port), so every 4-tuple is distinct. That client-side port (51834) is an ephemeral port — grabbed from a high range for the life of one connection.

ss -tlnp shows no line for port 8000. What have you just proven?

In an ESTAB line, which field holds the ephemeral (client-chosen) port?

Which invocation shows only sockets that are waiting for new connections?

Do it now: run the two commands above, then kill %1 to stop the server. Next we open the connection you just watched — three packets in, one of two ways out.

Fonte primária · leia em seguida

Networking! ACK! — Julia Evans (paid zine, one page per tool). Its ss/netstat page is the friendliest map of exactly this output.

Sou seu professor — traga suas perguntas difíceis de “mas por quê”. Exporte seu progresso na página do curso e cole no /teach.

04 / 11Anterior