Skip to content

3. Ports, Sockets and Default Ports

“The building has a thousand doors. Only the ones with someone behind them matter.”

It is a little after eleven on a Sunday night. Priya has just deployed the team-status tool to a small cloud box, and the deploy log ends in a cheerful green line. She opens the address on her laptop. It loads. She opens it on her phone, on Pune mobile data, and gets a white page that says the site can’t be reached. She types in the raw IP address of the server. Same white page. Back on the laptop, the same IP address works fine.

Nothing about the server changed between those attempts. Only the place the knock came from changed. That is the first clue, and it takes her the better part of an hour and two cups of chai to see it.

Let me give you the picture I wish someone had handed me years ago. Imagine a chai stall at the end of a lane in Pune. The stall has one counter, and the counter has a street address. Behind it are dozens of small numbered hatches. Hatch 80 is the window where the samosas come out. Hatch 22 is the owner’s private hatch, the one he uses to pass the cash box to his cousin. Hatch 3000 is a hatch somebody cut into the back wall last Tuesday, and nobody has told the regulars about it yet.

A customer walking up to the stall has to say which hatch they want. If nobody is standing behind that hatch, the customer gets silence or a shrug, not a locked building. Whether a knock on a hatch gets an answer depends on three things: whether someone is standing there, whether the lane lets the knock through, and whether the hatch was cut to face the lane or the inside of the shop.

That last part is what this chapter is about. Ports, sockets and binding answer one question: who is standing behind which door, and who is allowed to knock on it? Once you can read that, most of the “works on my machine” misery stops being mysterious. It also stops being frightening. You will still get the 2 a.m. call now and then, but you will be able to tell from the first sentence what kind of call it is.

Priya’s problem, as you will see, came down to one line of configuration and one assumption nobody had written down. The line is in the lab at the end of this chapter. The assumption is in the next few sections. We start with the hatches.

Here is the first thing to unlearn. A port is not a thing. There is no hatch on the back of the server and no little socket you can point at. A port is a number, sixteen bits wide, written into the header of every TCP and UDP packet. It runs from 0 to 65535, and that is the whole of it.

Why does the number exist at all? The IP address gets a packet to the right machine. Once the packet arrives, the machine has to decide which program should read it. One box might run a web server, a mail daemon, an SSH server and a dozen other things, and they all share one address. The port is the field that says which of them the packet is for. If the address is the building, the port is the office number painted on the door.

The convention is older than most of us, and the folklore around how each number was assigned is thicker than the documentation. I will not pretend to date each one from memory. What matters is that everybody agreed on the common ones. A client that wants a web page knocks on 80 or 443. A server that offers one listens there. That shared agreement is the only reason your browser does not need to be told where to look for every site.

Imagine the world without ports for a moment. One address and no port numbers would deliver a mail packet and a web request to the same place, and the machine would have to open each one and guess. Ports are the cheap answer that made one address serving many programs practical, and the cost is a single number in a header.

Now the word socket. A socket is the operating system’s handle for one end of a network conversation. It is made from an address, a protocol and a port, and it belongs to a program. When a program says, in effect, “I want knocks on port 3000,” the kernel creates a listening socket and hands the program a handle to it. The program then waits. When a client’s knock arrives, the kernel completes the handshake and creates a second, connected socket for that one conversation. The listening socket stays where it is, ready for the next visitor.

That is what listening means. It is not a special state of the network card or some hidden switch. It is a program telling the kernel that it will accept connections on an address and port, and the kernel holding a queue of people waiting at the door.

One conversation between a laptop and a serverA laptop on the left, using ephemeral source port 52814, sends a packet to a server on the right that listens on port 443. The reply travels back with the ports swapped, so both ends agree on which conversation it belongs to.Laptop192.168.1.7source port 52814the browserServer203.0.113.10listening on port 443one listening socket52814443dst 443, src 52814dst 52814, src 443The address pair and the port pair, plus TCP, name one conversation.
Figure 3.1. A conversation is named by two addresses, two ports and a protocol.

Each conversation has two ends, and each end has a port. The side that starts the conversation is the client, and its port is the source port. The side that answers is the server, and the port the client knocked on is the destination port. When your laptop loads a page, the packet it sends carries a destination port of 443. Its source port is a number that looks random, perhaps 52814. The server’s reply carries the two numbers swapped, so it lands back in the right conversation and nowhere else.

The four numbers that matter are the two addresses and the two ports. Add the protocol, TCP or UDP, and you have a five-part key that names exactly one conversation. The kernel uses that key to hand every returning packet to the right connected socket. That is why one server can serve thousands of visitors on port 443 at the same moment without mixing them up. The listening socket is one door. The conversations are many rooms behind it, each identified by its own key.

Ranges: well-known, registered and dynamic

Section titled “Ranges: well-known, registered and dynamic”

The 65,536 port numbers are not handed out equally. They fall into three bands, and the band a number sits in tells you who is supposed to be using it.

Well-known, 0 to 1023. These are the doors the world agreed on: 22 for SSH, 80 for plain HTTP, 443 for HTTPS. On most Unix-like systems, including the Ubuntu box in our lab, only root may bind a port in this band by default. The rule is old, and the story behind it is a widely told one about a time when any user on a shared machine could grab port 25 and pose as the mail server. Whatever the history, the effect is what you feel today. Your app, running as an ordinary user, cannot just listen on 80.

Registered, 1024 to 49151. Projects and vendors have agreed on numbers here by convention, and many of the familiar database and developer ports live in this band. Postgres sits on 5432 and Redis on 6379. Nothing stops an ordinary user from binding these, and nothing stops you from putting something else on 5432, but the number is a label that tells the next person what you probably meant.

Dynamic, 49152 to 65535. This band belongs, in spirit, to the client side. When your browser opens a conversation, the operating system picks a source port from a pool of high numbers. Linux’s default pool sits lower than this band, roughly from the low 30,000s to the low 60,000s if memory serves, and the range is a setting you can change. What matters is that you did not pick the number. The kernel picked it, for this conversation only.

That is what ephemeral means: short-lived. An ephemeral port lives as long as one conversation does. Your laptop might use 52814 for one page load and 52815 for the next. The server does not care which number you used, because it replies to whatever arrived.

The 65,536 port numbers split into three bandsA horizontal bar from 0 to 65535. A thin sliver at the left is the well-known band, 0 to 1023. The large middle section is the registered band, 1024 to 49151. The right section is the dynamic band, 49152 to 65535, which holds client source ports.0 to 1023, well-known1024 to 49151, registereddatabases and developer tools, by convention49152 to 65535dynamic, client side04915265535Well-known needs root to bind. Client source ports come from the top band.
Figure 3.2. The port space is split into three bands, and only the first one needs root.

Every reachability problem in this book, and most of the ones you will meet at 2 a.m., can be walked down the same ladder. Say it out loud a few times until it sounds like a chant:

Name → Address → Route → Door → Guard → Receptionist → App

Each word is a rung, and each rung asks exactly one question. Start at the top. Climb down. Stop at the first rung that fails. The fault lives at that rung. The rungs below it cannot be tested until it is fixed, because they never receive the knock.

The mantra as a ladder of seven rungsSeven boxes stacked from top to bottom, labelled Name, Address, Route, Door, Guard, Receptionist and App. Beside each one is the single question asked at that rung. Arrows point down the ladder to show the order of the checks.NameDoes the name turn into an address?AddressDoes that address point at the right building?RouteIs there a road there and a road back?DoorIs anything listening on this port?GuardDoes a firewall let this knock through?ReceptionistDoes the proxy pass it to the right app?AppDoes the program answer correctly?Climb from the top. The first rung that fails is where the fault lives.
Figure 3.3. The mantra. One question per rung, climbed from the top until the first failure.

Here are the questions, in order.

Name asks whether the name turns into an address. Priya’s first attempt skipped this rung on purpose by typing a raw IP, and that is why her second attempt told her something useful. The name was not the problem. We give the city directory its own chapter in Chapter 10.

Address asks whether the number points at the right building. A correct name that points at an old address is a classic way to knock on a building you no longer own.

Route asks whether packets have a road there and a road back. Chapter 2 walked the roads. A route that goes out and never returns looks, from your side, exactly like a locked door.

Door asks whether anything is listening on the port you knocked on. This is the question this chapter exists to answer.

Guard asks whether a firewall lets this knock through. The guard has a clipboard. He checks the source and the door against his list, and if the knock is not on it he does not say no. He says nothing at all, and that silence is the timeout you will meet shortly.

Receptionist asks whether a reverse proxy sits in front of the app and passes the request to the right place. Chapter 8 gives her a proper introduction.

App asks whether the program behind the door answered correctly. Only at this rung does the question become about your code. Everything above it is about the plumbing.

The order matters because each rung is a precondition for the next. You cannot ask whether the app answers if the knock never reached the door. That sounds obvious, and yet most of the wasted afternoons in debugging stories begin with someone staring at the App rung while the Guard rung quietly binned every packet.

The mantra also tells you which tool to reach for. The Name rung wants a directory lookup. The Route rung wants a trace. The Door rung wants a list of listening sockets. The App rung wants a request you can read. You will use all four in the lab, and you will be less frightened of them afterwards.

Binding: the one line behind most “can’t reach it” problems

Section titled “Binding: the one line behind most “can’t reach it” problems”

A program that wants visitors has to tell the operating system so. The word for that is binding, or listening, which is the same act seen from the other side. The program hands the kernel an address and a port and says: anything arriving for this pair is mine.

The address half is where people get hurt. Two forms turn up constantly.

127.0.0.1:3000 binds to the loopback address. Think of it as the building’s internal intercom. Only processes on the same machine can reach it. Your browser on the same laptop can. A phone on the same Wi-Fi cannot, because the knock is aimed at an address that only means “this machine, from the inside”.

0.0.0.0:3000 means every address the machine has: loopback, the private address, the public address, anything else attached. The program is now on the street, reachable by anyone the rest of the path lets through.

Many dev servers bind to localhost by default, and some frameworks switch to a wider bind with a flag or an environment variable. That is why the same app behaves differently on two machines. Check the bind address before you touch any firewall. A large share of “I deployed it and nothing answers” stories are a program still on loopback, running happily, with nobody able to reach it.

The expensive mistake runs the other way. A database bound to 0.0.0.0:5432, with the firewall rule that was meant to close it forgotten, or a container port published without a second thought, is how a great many exposed-database stories begin.

Our recommendation for a small production VPS: bind the app to 127.0.0.1 and let the reverse proxy from Chapter 8 be the only door the public sees. Bind databases to loopback or the private address only. The firewall is the second lock, not the first.

Binding to loopback versus all addressesLeft: the app listens on 127.0.0.1, so the laptop inside reaches its door and the phone outside bounces off the wall. Right: the app listens on 0.0.0.0, so the same door opens onto the street and the phone gets in.Bound to 127.0.0.1:3000only this machine can knockBound to 0.0.0.0:3000every address, the street includedapp3000laptopphonerefusedapp3000phonereached
Figure 3.4. The same app on the same port. Only the bind address decides who can knock.

Source ports, destination ports and the ephemeral ones

Section titled “Source ports, destination ports and the ephemeral ones”

Every conversation has two ends, so every conversation carries two port numbers. The destination port is the door you knock on. It is the number the server listens on, and it is the one you normally type, or the one your browser assumes. The source port belongs to your side. It is the return slip tucked into the knock, so the replies know which conversation they belong to.

Your laptop does not keep a fixed source port. When your browser opens a connection to a site on 443, the operating system takes a free number from a pool of temporary ports and uses it for that one conversation. These are ephemeral ports, because they last only as long as the conversation does. The number is disposable. Nothing listens on it for you.

On Linux the default pool is roughly 32768 to 60999. Other systems use other ranges, and they have moved them over the years, so treat the exact figures as a rough guide. The principle is what to remember: the client’s port is almost always random and short-lived, and the server’s port is almost always fixed and published.

This is why one laptop can hold hundreds of connections to the same server at once. Each one has its own pair: your address with an ephemeral port on one side, the server’s address with its fixed port on the other. Two tabs open to the same site are two different pairs, and so are two requests in one tab. The pair is the conversation’s identity, and the operating system keeps the ledger.

It is also why a monitoring screen full of connections can look alarming. Most of those numbers are yours. They belong to your own browser, politely knocking and waiting for the answer.

Some ports are so common they have become folklore. Others are a standing invitation to trouble. The table covers the ones you will meet in this book. For each, ask the same question: should a stranger on the street be able to knock here?

Port Service What it is Open to the whole internet?
20, 21 FTP File transfer. 21 carries commands, 20 the data in classic mode. No. Plaintext logins and files.
22 SSH Encrypted remote shell and file copy. Expected on servers you run. Keys only, or it gets guessed at all day.
23 Telnet Old remote shell with no encryption. No. Anyone on the path reads the password.
25 SMTP Mail passed between servers. Yes for a mail server. Otherwise a spam relay waiting to happen.
465, 587 SMTP submission Sending mail from your app, with login. 465 is TLS from the start, 587 usually upgrades. No. Your mail client needs it, the world does not.
53 DNS Name lookups. Only for a resolver you mean to run for others.
80 HTTP Plain web traffic. Yes, usually just to redirect people to 443.
110, 143, 993 POP3, IMAP Reading a mailbox. 993 is IMAP over TLS. 110 and 143 are the plain versions. Mail clients only. Plain versions should not carry passwords.
123 NTP Clock synchronisation, over UDP. Fine for a public time server. Misconfigured ones get abused.
443 HTTPS Encrypted web traffic. Yes. That is the point. The UDP 443 twin carries HTTP/3.
3000 Node and Next dev server, by convention Development server. No. Dev servers are not built to be hardened.
5173 Vite dev server Development server. No. Same answer as 3000.
8080, 8000 Alternative HTTP Often a proxy, an app behind one, or a dev server. Only behind a front door you trust.
3306 MySQL, MariaDB Database. No. A password is the only lock, and scanners try them constantly.
5432 PostgreSQL Database. No. Same reasoning as 3306.
6379 Redis In-memory store. No. Older installs shipped with no password and listened on every interface.
27017 MongoDB Database. No. Exposed instances have been held for ransom, in a widely told story.
9200 Elasticsearch Search and analytics API. No. Exposed clusters have been wiped by strangers.
2375, 2376 Docker API Control the Docker daemon. No. Unencrypted 2375 is root on the host with extra steps. 2376 adds TLS.
51820 WireGuard VPN over UDP. Designed to stay silent toward strangers, so it can face the internet.
41641 Tailscale Its usual UDP port for direct connections, as far as memory serves. You do not need to open it. Tailscale finds its own way.

Two things to take from the table. First, the number tells you what the server expects you to speak, not what it really is. Nothing stops you running a database on port 443, and the clients will fail to make sense of it. Second, the danger is rarely the number itself. It is an open door combined with a service that trusts whoever knocks.

Almost every failed connection hands you one of three sentences, and most people hear them all as “it’s broken.” They are three different sentences. Each one tells you which rung of the ladder failed, so learn to read them the way a doctor reads a temperature chart.

Connection refused means your packet reached the host, and the host answered straight away with a polite no. The reply came back almost at once, which is the network telling you the building exists, the route works, and nobody is at that door. Either nothing is listening on that port, or the thing that is listening is bound to some other address. A refusal is good news. You have already passed the route and the guard, so the problem sits at the door or just behind it.

Connection timed out means silence. Your SYN went out and nothing came back, not even a no. Somewhere a guard (a firewall rule, a cloud security group, a network ACL) dropped the packet without a word, or the route is broken, or the host is off the network. Your laptop waits, retries, and eventually gives up, which is why this one feels slow. Timeouts are the expensive error, because they cost you seconds per attempt and they do not say which layer failed.

Connection reset is the strangest of the three and the most informative once you know it. The handshake worked. Something accepted the connection, you started talking, and then something slammed the door mid-sentence. A reset from the server usually means the process crashed or closed its socket, a reverse proxy gave up on the app behind it, or the process at the door speaks a different protocol from the one you sent. The port is right. The thing behind it is wrong.

Refused, timed out and reset comparedThree sequences from a laptop on the left to a server on the right. Refused: the server sends a reset at once, so nothing is listening. Timed out: the knock is dropped and nothing comes back. Reset: the connection opens, then the server sends a reset in the middle of the conversation.You (laptop)Server1. Refused: reached the host, nothing at that doorSYN to port 3000RST: nobody is listening on 30002. Timed out: the knock was dropped without a wordSYN to port 3000No reply. The client retries, then gives up.3. Reset: accepted, then slammed shut mid-conversationConnection accepted, requests flowingRST: the server shuts the door
Figure 3.5. Three errors, three different sentences from the network. Each one points at a different rung.

Read each error as a rung. Refused lands on the Door rung: the port is closed or unclaimed. Timed out lands on the Guard rung, or on the route before it. Reset lands on the Receptionist or the App: something answered and then gave up. That is the mantra doing its job. One error, one question, one place to look. When something fails, do not guess. Climb from the top and stop at the first rung that gives you the wrong answer.

Sooner or later every operator asks this, usually after a week of auth logs that look like a dog barking at the gate all night. Moving SSH to a random high port such as 2222 or 40022 cuts that noise sharply. Most automated scanners sweep the famous doors first, and a quiet high port rarely makes their list.

Be clear about what you bought, though. A patient scanner that sweeps the whole range will find SSH on the new port within a day or so. Moving the door changes the log. It does not change the lock.

The real defence is key-only authentication. Turn password logins off, keep direct root login off, and make sure the only thing the server accepts is a key that you hold. A password can be guessed given enough attempts. A key that nobody else has a copy of cannot be guessed at all. Keep port 22 if you like, and spend your effort on the lock. Chapter 6 and Appendix D walk through the settings line by line.

Seeing what is listening: reading the socket table

Section titled “Seeing what is listening: reading the socket table”

On a server, one command tells you which doors are open and who is standing behind each one. Ask ss for the listening TCP sockets with process names, and the output looks like this:

State Recv-Q Send-Q Local Address:Port Peer Address:Port Process
LISTEN 0 511 127.0.0.1:3000 0.0.0.0:* users:(("node",pid=4182,fd=21))
LISTEN 0 128 0.0.0.0:22 0.0.0.0:* users:(("sshd",pid=811,fd=3))
LISTEN 0 511 [::]:443 [::]:* users:(("nginx",pid=1290,fd=6))

Read it column by column:

  • State. LISTEN means a socket is waiting for a knock. Rows in other states, such as ESTAB for established, are conversations already under way.
  • Local Address:Port. This is the column that matters. 127.0.0.1:3000 means the Node app is bound to loopback, so only processes on this same machine can reach it. 0.0.0.0:22 means SSH listens on every IPv4 address. [::]:443 is the IPv6 wildcard, which on most Linux systems also accepts IPv4.
  • Recv-Q and Send-Q. Queue sizes. Ignore them most days. A Recv-Q that keeps climbing on a LISTEN row is the first sign of an app that cannot keep up.
  • Process. The program that owns the door, with its process id and file descriptor. When you cannot remember what is on 8080, this column answers in one line.

If a service is missing from this table, nothing is listening, and no amount of firewall tuning will bring it back. That is the first rung of the mantra, and it is the cheapest question you will ever ask.

Goal. See the difference between a loopback bind and a wildcard bind with your own eyes, and produce each of the three errors on purpose.

Conceptual steps.

  1. Write a tiny app called hello-pipes that prints the Host header and the client address it sees on every request. Keep it. It is the most useful debugging tool in this book.
  2. Start it listening on loopback only, on port 3000. From the laptop, ask whether you can reach it. Then, from your phone on the same Wi-Fi, try the laptop’s LAN address. Note which rung fails.
  3. Restart it listening on all addresses, on the same port. Repeat both checks. The phone should now get in.
  4. Read the socket table on the laptop and find your app’s row. Check that its Local Address matches what you just observed.
  5. Produce the three errors on purpose. For refused, ask for a port that nothing listens on. For timed out, aim at a private address on a network you are not on, and wait. For reset, write a tiny server that accepts the connection and then closes it without a reply. Write down which error each attempt gave you and which rung it answered.

Binding to all addresses opens the app to your home network, so do this on a network you trust, and close the server when you finish.

How you’ll know it worked. Before you press enter, you can predict which of the three errors a given mistake will produce. Your phone gets in only when the bind is a wildcard, and the socket table tells the same story as your tests. When you can say, in one sentence each, why refused is good news and why timed out is a silence, the lab has done its job. Chapter 4 repeats the exercise on the lab VPS, where the door faces the whole internet.

A port is a number written on the envelope, not a socket in the wall. Two addresses, two ports and a protocol name a conversation. The server side of that conversation is a socket that a program has bound to an address and a port, and “listening” is the program saying, out loud, that it will take knocks there.

Binding is where most of the trouble lives. 127.0.0.1 means “this machine only”, and 0.0.0.0 means “every address this machine has”. The same app on the same port can be a private desk or a shop front, and nothing in its code looks different between the two. The socket table tells you which one you have, so read it before you blame the firewall.

When a knock fails, you now have three sentences to choose from. Refused means the building answered and nobody is at that door. Timed out means the knock vanished, so something between you and the building is dropping it. Reset means something opened the door and then slammed it. Each sentence points at a different rung of the mantra, Name → Address → Route → Door → Guard → Receptionist → App, and you climb it from the top until the first rung that fails.

Default ports are habits, not laws. Port 443 is HTTPS because the web agreed on it, and 5432 is Postgres because someone picked it once and everyone kept it. Treat the list as a map of what to expect. An open port tells you what is running, never whether it should be running.

1. A browser connects to a server on port 443. Which port does the browser use?

Not 443. The browser gets an ephemeral source port from the dynamic range, chosen by its operating system for that one conversation. Port 443 is the destination. The server replies to the source port, which is how both halves of the conversation find each other.

2. Your app logs listening on 127.0.0.1:3000. Can a phone on the same Wi-Fi reach it?

No. The socket is bound to loopback, so the laptop’s operating system has nothing waiting on its LAN address. The phone will most likely get connection refused. Rebinding to 0.0.0.0:3000 opens the app to every address the machine has, which is what you want only when you mean it.

3. Your curl to port 5432 says connection refused. What does that tell you about the rungs above the door?

It tells you the name resolved and the address and route worked, and that something on the path actively answered no. Nothing is listening on that port, or it is bound to an address you did not expect. A firewall set to reject rather than drop can also produce this, and it is still a refusal. Check the Door rung first: is Postgres bound, and to which address?

4. Your curl says connection timed out. Where do you look first?

At the guard and the route. Silence means the knock was dropped without an answer, so the app may be perfectly healthy and never saw the request. Check the cloud firewall, the host firewall and the routing between you and the server, in that order of how often they bite.

5. Your curl says connection reset. What happened?

Something accepted the connection and then tore it down. Usually the app or a proxy got past the door and then failed: plain HTTP sent to a TLS port, a process that crashed mid-request, or a reverse proxy with no healthy backend behind it. Look at the Receptionist and App rungs. The network did its job; the thing behind it did not.

6. Should you move SSH off port 22?

Only if you want quieter logs, and be honest with yourself about what that buys. Moving the port cuts the drive-by noise in your auth log. It does not stop a determined attacker who scans every port. Key-only logins, with password logins switched off, are the real defence, and a firewall that admits only the sources you trust is the second layer.

7. Why is a database on 5432 or a Redis on 6379 a problem when it is open to the world?

Because the door is the only thing between a stranger and the data, and many of these services were built to trust anyone who could knock. A widely told story describes an unauthenticated Redis left on the open internet and taken over within hours. Bind databases and caches to loopback or a private network, and let the guard say no to everyone else.

Three of these need no machine at all. The lab ones run on your laptop, and nothing here needs the VPS yet. Answer in your head first, then open the answer.

Warm-up 1. Name the rungs. A colleague says “the site is down”. Walk the mantra, Name → Address → Route → Door → Guard → Receptionist → App, and write the one question you would ask at each rung.

Answer

Name: does the hostname resolve, and to which address? Address: is that the right machine? Route: can packets get there and back? Door: is something bound to the port? Guard: does a firewall admit the knock? Receptionist: does the reverse proxy forward it? App: does the application answer? Most “site is down” reports die on one of the first four rungs. The last three are where your own bugs usually live.

Warm-up 2. Source or destination? Your browser opens a connection to pipeslab.in on port 443. Which port is the source and which is the destination? Why does the server’s reply find the right browser tab?

Answer

The destination is 443, the well-known HTTPS port on the server. The source is an ephemeral port that your operating system picked from the dynamic range for this one conversation. The server copies the source port into its reply, and your operating system uses that number to hand the packets to the right tab. The server never needs to know which tab it was.

Warm-up 3. Read the three sentences. Match each message to its meaning: connection refused, connection timed out, connection reset. Then say which one is the good news, and why.

Answer

Refused means the host answered and nothing is at that door: the building is there and the room is empty. Timed out means the knock vanished without a reply, which points at a firewall dropping packets or a routing problem. Reset means something accepted the connection and then tore it down. Refused is the good news. It proves the name, the address and the route all worked, so you can stop checking them.

Lab 4. Hear the difference. Write a tiny server that listens on 127.0.0.1:3000. Check that it answers on the laptop, then try the same address from your phone on the same Wi-Fi. Change the bind to 0.0.0.0:3000, try again, and write down what changed.

Hint

Any language will do, and a one-line Node server is enough. Check the laptop with curl against 127.0.0.1. For the phone, use the laptop’s LAN address, which is 192.168.1.7 in the lab world. Read the listening address with ss -tlnp on Linux, or lsof -iTCP -sTCP:LISTEN -n -P on macOS.

Model solution

Bound to loopback, the laptop answers itself, and the phone gets connection refused when it knocks on the LAN address. After you rebind to 0.0.0.0:3000, the listing shows the port on every address, and the phone gets the page. The code did not change. Only the bind address changed, and that one argument decided who could knock.

Lab 5. Make a timeout on purpose. Send a request to an address that will never answer, using a 5-second limit. Read the error. Then say which rung you would suspect, and why you cannot tell from the message alone which device dropped it.

Hint

Use the documentation range 192.0.2.1 on port 80, and give curl a --max-time 5 limit with verbose output. Your home router may answer with “no route to host” instead of a silent drop. If it does, say so in your notes, because that is a different sentence with a different owner.

Model solution

The request hangs for about 5 seconds, then fails with a timeout. The knock was dropped with no reply, so the suspects are the route and any firewall on the path. The message does not say which device binned it. Only a traceroute, or a check from a second network, narrows that down. If you got “no route to host” instead, the message named your own router as the one that refused to forward.

Lab 6. Make a reset on purpose. Write a server that accepts a connection and then closes it at once, without sending anything. Ask it for a page with curl and read the message you get. Put it next to the refusal from Exercise 4 and the timeout from Exercise 5. In one sentence, say which of the three rungs of the ladder the reset came from.

Hint

Use Node’s net module rather than http. net.createServer hands you a socket the moment a client connects. Call socket.destroy() straight away, before writing anything. Listen on port 3001 so you do not clash with anything else. In a second terminal, run curl http://127.0.0.1:3001/. On macOS you will most likely see Empty reply from server or a Recv failure: Connection reset by peer line. Both come from the same event: the other side closed the door mid-conversation.

Model solution

The TCP handshake succeeded, so the port was open and a process owned it. The process then closed the socket before sending any HTTP response. Your client was waiting for bytes and got an early close or a reset instead. The reset came from the Door and Receptionist rungs, not from a firewall. The difference from a refusal is who answered. A refusal means the host itself said nobody is listening. A reset means a program accepted you and then slammed the door. That is why a reset is the hardest of the three to read at first glance.

Lab 7. Read the listener table. Start two small servers on your laptop: one bound to 127.0.0.1 on port 3000, and one bound to 0.0.0.0 on port 3001. Then list every listening socket on the machine. For each of your two servers, point to the column that shows the bind address, the column that shows the port, and the column that names the process. Explain in your own words why the first server does not appear to the outside world even though both are running.

Hint

On Linux, ss -tlnp prints the listening TCP sockets with their processes. On macOS, use lsof -iTCP -sTCP:LISTEN -n -P. Look for the lines that mention your port numbers. In the local-address column, 127.0.0.1:3000 and *:3001 tell you almost everything you need. The * means all addresses, the same as 0.0.0.0.

Model solution

The local address column holds the bind address and the port together, separated by the last colon. On the loopback server it reads 127.0.0.1:3000, which is a door that only faces the inside of the machine. On the other server it reads *:3001 or 0.0.0.0:3001, which is a door on every street-facing interface. The process column names the program, for example node, along with its process ID. The loopback server does not appear to the outside world because the kernel only delivers packets for 127.0.0.1 to sockets bound there, and packets arriving on the public address never reach it. Your listener table is the fastest way to answer “what is actually exposed,” so get used to reading it before you read any firewall rules.

Staff 8. Does the firewall protect a published port? Your VPS runs ufw with a rule that denies inbound 5432. You start a Postgres container with -p 5432:5432. Someone on the internet connects to port 5432 and gets a password prompt. Explain how that happened, and say what single change to the port mapping fixes it.

Model answer

Docker writes its own rules into the firewall’s NAT and forwarding chains when you publish a port. Those rules run ahead of the rules that ufw manages, so the traffic is forwarded to the container before your deny rule is consulted. Your ufw rule looked correct on paper and was never reached for this traffic. This is the Docker bypass we return to in Chapter 7. The fix is to bind the publish to loopback: 127.0.0.1:5432:5432. Then only processes on the VPS itself can reach it, and the database is no longer on the street. Even better, for a database that only your app needs, do not publish it at all, and let the app reach it over a shared Docker network. Verify the result from outside the VPS, not from inside it. An inside check tells you nothing about the street door.

Staff 9. Loopback or all addresses? Your Node app listens on 0.0.0.0:3000 behind nginx on port 443. A colleague says the bind address does not matter because nginx is the only thing that talks to it. Give two reasons the colleague is wrong, then describe the one case where binding to all addresses is the correct choice.

Model answer

First, 0.0.0.0 makes the app reachable from every interface, including the public one. If your firewall ever has a gap, or someone adds a port mapping later, the app is exposed with no extra step, which is the quiet way most internal services end up on the internet. Second, binding to 127.0.0.1 makes the design explicit. The app can only be reached by something on the same machine, and nginx is that something. The bind address documents your intent, and it fails safe when a rule changes. The one good case for 0.0.0.0 is inside a container. A process in a container must listen on all of its interfaces, because the port mapping from the host arrives on the container’s bridge address rather than loopback. The mapping is then the thing you control, and you should bind it to loopback on the host, as in Exercise 8. We come back to this in Chapters 14 and 15.

Book 2 of a series. Book 1: The Glue.