Servers, Ports and Sockets: What Is Listening and Who Can Reach It
See how a server program listens on a port: start real servers, read the kernel's list of listening sockets, learn the difference between binding to localhost and to all addresses, and watch the real errors for a busy port and a closed port.
In this lesson you will
- Explain what a port is
- Tell localhost from all-interfaces binding
- Read the list of listening sockets
- Recognise “address in use” and “connection refused”
About 28 minutes
A server is a program waiting at a door
A server in the everyday sense is a computer, and a server in the technical sense is a program that waits for requests. Every machine on a network has addresses, and each program that wants to receive connections claims a port, a number from 0 to 65,535, on one or more of those addresses. A web server normally listens on port 80 for plain HTTP and 443 for HTTPS, SSH uses 22 and mail uses 25. When a visitor types an address, the browser connects to the server’s address at the port, and the operating system hands the connection to the program listening there. Only one program can listen on a given address and port at a time.
Where a program listens matters for security. A server bound to 127.0.0.1, the loopback address, can only be reached from the same machine, which is right for a database that only your web server needs. A server bound to 0.0.0.0 listens on every address of the machine and can be reached from the network, subject to the firewall. Many incidents come from a database that was meant to be private and was bound to all addresses. The kernel keeps a table of sockets, readable on Linux in /proc/net/tcp, and tools such as ss and netstat show it in a friendly form. Two errors tell you most of what you need to know when something does not work: “address already in use” means that another program holds the port, and “connection refused” means that nothing is listening at that address and port.
| Binding | Reachable from | Typical use |
|---|---|---|
| 127.0.0.1:5432 | This machine only | Database used by the app |
| 0.0.0.0:443 | Any network address of the machine | Public web server |
| 192.168.1.5:8080 | One specific interface | Internal service |
| Port below 1024 | Needs administrator rights on many systems | 80, 443, 22 |
import socket, threading, subprocess, json
def listen(host):
s = socket.socket(); s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1); s.bind((host, 0)); s.listen(5); return s, s.getsockname()[1]
a, pa = listen("127.0.0.1"); b, pb = listen("0.0.0.0")
def proc_listeners():
out = {}
for line in open("/proc/net/tcp").read().splitlines()[1:]:
f = line.split()
if f[3] == "0A": # state 0A = LISTEN
ip_hex, port_hex = f[1].split(":"); ip = ".".join(str(int(ip_hex[i:i + 2], 16)) for i in (6, 4, 2, 0)); out[int(port_hex, 16)] = ip
return out
seen = proc_listeners()
print("kernel says port %d is bound to %s and port %d to %s" % (pa, seen[pa], pb, seen[pb]))
try:
c = socket.socket(); c.bind(("127.0.0.1", pa)); busy = "bound"
except OSError as e: busy = e.strerror
print("binding the same address and port again:", busy)
closed = socket.socket(); closed.bind(("127.0.0.1", 0)); free_port = closed.getsockname()[1]; closed.close()
r = socket.socket(); refused = r.connect_ex(("127.0.0.1", free_port)); r.close()
print("connecting to a port nobody listens on: error code", refused, "=", __import__("os").strerror(refused))
ok = socket.socket(); up = ok.connect_ex(("127.0.0.1", pa)); ok.close()
curl = subprocess.run(["curl", "-s", "-o", "/dev/null", "-m", "2", "-w", "%{exitcode}", "http://127.0.0.1:%d/" % free_port], capture_output=True, text=True).stdout
print("connecting to the listening port: error code", up, "(0 = connected) | curl to the closed port exits with", curl, "(7 = could not connect)")
print("DATA " + json.dumps({"a": seen[pa], "b": seen[pb], "busy": busy, "refused": refused, "up": up, "curl": curl}))
kernel says port 41893 is bound to 127.0.0.1 and port 38345 to 0.0.0.0
binding the same address and port again: Address already in use
connecting to a port nobody listens on: error code 111 = Connection refused
connecting to the listening port: error code 0 (0 = connected) | curl to the closed port exits with 7 (7 = could not connect)
The program opened two listening sockets, one bound to 127.0.0.1 and one to 0.0.0.0, and then read the kernel’s own table of sockets from /proc/net/tcp, where addresses are written in hexadecimal with the bytes reversed. The kernel confirms the bindings: the first port is bound to 127.0.0.1, reachable only from this machine, and the second to 0.0.0.0, which means all addresses. Trying to bind the same address and port a second time failed with the message “Address already in use”, the error that appears when you start a second copy of a server. Connecting to a port that nobody listens on failed with error code 111, “Connection refused”, while connecting to the listening port succeeded (code 0).
curl, a separate program, was pointed at the closed port and exited with status 7, which curl documents as “failed to connect to host”. The same two messages are what you will see in a browser as “This site can’t be reached” when a server is down, or in your own logs when a service does not start. A quick way to separate causes is the question “is something listening?”: if the connection is refused, the program is not running or listens elsewhere, and if the connection hangs until a timeout, a firewall is probably dropping the packets.
Independent check: the kernel table was read directly by the program and also confirmed by behaviour, since connect_ex succeeded on the port that the table lists as listening and failed with code 111 on the port that is absent from it, and curl agreed with the failure. Three views of the same fact, the table, a connection attempt and another tool, agree. On a real server you would use ss -ltnp, which shows the same table with the program names.
Check by hand: the address 0100007F in /proc/net/tcp is read as bytes 01, 00, 00, 7F from the right: 7F 00 00 01, which is 127.0.0.1, and 00000000 is 0.0.0.0. The state code 0A means LISTEN. Error code 111 on Linux is ECONNREFUSED and 98 is EADDRINUSE.
Bind databases and caches to 127.0.0.1 or a private network, and block their ports in the firewall. Public databases are found and attacked within hours.
When a service is unreachable, list the listening sockets before anything else. It separates “not running”, “wrong address” and “blocked” in seconds.
Providers, plans and prices change often, so the lessons use invented prices and generic names, and you must check each provider’s current website. The server behaviour in this lesson was run for real on a Linux machine with Python 3.13, Node.js 22, OpenSSL and standard Unix tools, and every result was checked a second way. Tools such as ss and netstat show the same table. The program here reads /proc directly because it needs no extra tools.
Practice
Start two copies of a server on the same port and read the error. List the listening ports of your own computer with ss -ltn. Find which program listens on port 22, if any.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
What is a port?
- A cable
- A kind of server
- A number that identifies a program’s door on an address
- A domain
0 to 65,535.
What does binding to 127.0.0.1 mean?
- Reachable from everywhere
- Reachable only from the same machine
- Blocked
- Encrypted
Loopback.
What does “address already in use” mean?
- The server is fast
- Another program holds that address and port
- The disk is full
- The password is wrong
Only one listener at a time.
What does “connection refused” mean?
- Nothing is listening there
- The password is wrong
- The file is missing
- The page is slow
Error 111 on Linux.
Why read the kernel table directly?
- It shows the true state of the sockets
- It is fashionable
- It is slower
- It hides ports
Same as ss.
Summary
- A port identifies a program’s door on an address.
- Bind private services to localhost.
- The kernel keeps the list of listening sockets.
- Address in use and connection refused have different causes.
Questions
Which ports are public?
Those that a program listens on and that the firewall allows. Use the minimum, usually 80 and 443 for a web server and 22 for administration, and restrict 22 where possible.
Can two programs share a port?
Not on the same address, except with special options such as SO_REUSEPORT. A reverse proxy lets several sites share 80 and 443.
What is localhost?
A name for the loopback address 127.0.0.1 on your own machine.
