Courses3 levels
Level 1 · Foundations11 courses
Level 2 · Core5 courses
Level 3 · Advanced5 courses
Labs8 topics
Library Practice exams AI Range Pricing Start free

Lesson 05 · 35 minutes

Start a server and watch a connection

After this lesson you can
  • Explain a port, a socket, and the difference between TCP and UDP
  • Start a local server and find it with ss
  • Connect to it from Python and recognise a refused connection
Lab files of this lesson (23)

The lab folder as it stands after this lesson. Unzip it in ~/krlab.

More

The zip holds every file that the course has printed up to here. To start this lesson with the files of the earlier lessons only, take the zip of the lesson before. Type the code yourself first: you learn more.

Scenario

A colleague tells you: "A test box in the lab runs a few small services on the ports 8040 to 8049. I do not know which ones, and nobody wrote it down." You must find out which ports accept a connection and what each service says when you connect. The box is your own machine, and the services are started by a script that you get in this lesson.

Recall

What does the address 127.0.0.1 mean, and does traffic to it leave the machine?

It is the loopback address: "this machine". The traffic never leaves the machine, so it needs no cable and no network.

Your machine is 10.1.1.5/24. Is 10.1.2.5 on the same network?

No. In a /24 the first three numbers are fixed. The third number differs (1 and 2), so the addresses are on different networks and the packet goes to the gateway.

The idea

An address finds a machine. A port finds the program on it. A port is a number from 0 to 65535. A program that wants to receive traffic asks the kernel for a port. A socket is the kernel's object for one end of a conversation: it holds an address, a port and a protocol. A connection is named by four values: the address and port of each end.

There are two main transport protocols:

TCPUDP
ConnectionYes: set up first, closed at the endNo: each packet stands alone
DeliveryOrdered, repeated if lostNo promise: a packet can be lost or arrive twice
Used forWeb, mail, SSH, databasesDNS, video calls, games, VPN

TCP starts with the three-way handshake. Only after it does data flow.

The TCP handshake, then data
ClientServerSYN, I want to talkSYN-ACK, I agree, here is mineACK, receiveddata: GET / HTTP/1.1data: the pageClientServer12345
  1. Client → Server: SYN, I want to talk
  2. Server → Client: SYN-ACK, I agree, here is mine
  3. Client → Server: ACK, received
  4. Client → Server: data: GET / HTTP/1.1
  5. Server → Client: data: the page

If nothing listens on the port, the kernel of the server answers the SYN with a reset: connection refused. If a firewall drops the packet, the client sees nothing until a timeout. This is a useful clue: refused means "the host is there, the port is closed"; a timeout means "something is hiding or dropping".

Three answers to one SYN
Your machineServer hostClientOpen portClosed portFirewalled port123Your machineServer hostClientOpen portClosed portFirewalledport123
  1. Client → Open port: SYN, then SYN-ACK: connected
  2. Client → Closed port: SYN, then a reset: refused
  3. Client → Firewalled port (blocked): SYN dropped, no answer: timeout

A socket is in one of two main states. A listening socket waits for new clients. An established (connected) socket is one live conversation. One listening port can serve many connected sockets.

Worked example

1. Make a page to serve

echo prints the text that you give it, and the sign > puts that text into a file. The page is the file that the server will send.

cd ~/krlab/networking
echo "hello from krlab" > index.html

2. Start a server on the loopback

python3 -m http.server runs the web server module that comes with Python (-m means "run a module"). It serves the files of the current folder. The number is the port. --bind 127.0.0.1 makes the server reachable from this machine only. Leave it running and open a second terminal for the next steps.

python3 -m http.server 8000 --bind 127.0.0.1
Serving HTTP on 127.0.0.1 port 8000 (http://127.0.0.1:8000/) ...

3. Find the listening socket

In the second terminal, ss (socket statistics) lists sockets. -t is TCP, -l is listening, -n keeps numbers instead of names, and -p shows the process. grep 8000 keeps only the lines that contain 8000, and the sign | gives the output of ss to grep.

ss -tlnp | grep 8000
LISTEN 0      5          127.0.0.1:8000       0.0.0.0:*    users:(("python3",pid=637312,fd=3))
One line of ss -tlnp
LISTENstate: waits for clients127.0.0.1:8000local end: address and port0.0.0.0:*other end: anyoneusers:(("python3",pid=637312,fd=3))the processLISTENstate: waits for clients127.0.0.1:8000local end: address and port0.0.0.0:*other end: anyoneusers:(("python3",pid=637312,fd=3))the process

Showing the process of your own programs needs no special rights. For the programs of other users you need sudo.

4. Connect from Python

Python's socket module is the same interface that every network program uses. create_connection opens a TCP connection. Write client.py. It prints both ends, sends a request and prints the first line of the answer. getsockname is your end and getpeername is the other end.

client.py

import socket

with socket.create_connection(("127.0.0.1", 8000), timeout=3) as s:
    print("local end :", s.getsockname())
    print("remote end:", s.getpeername())
    s.sendall(b"GET / HTTP/1.0\r\nHost: 127.0.0.1\r\n\r\n")
    data = s.recv(4096)
print(data.decode().splitlines()[0])
python3 client.py
local end : ('127.0.0.1', 35696)
remote end: ('127.0.0.1', 8000)
HTTP/1.0 200 OK

The server end is the port you chose. Your end is a port that the kernel chose from a high range (an ephemeral port). It changes on every run.

5. See a connected socket

Hold a connection open and look at it. This command opens one connection, then runs ss while the connection is still open. The filter dport = :8000 selects connections whose destination port is 8000.

python3 -c "
import socket, subprocess
s = socket.create_connection(('127.0.0.1', 8000))
subprocess.run(['ss', '-tn', 'state', 'established', 'dport', '=', ':8000'])
"
Recv-Q Send-Q Local Address:Port  Peer Address:Port
0      0          127.0.0.1:41284    127.0.0.1:8000

The server has the matching entry with the two ends swapped. In a full ss -tan listing, one connection appears twice, once from the client side and once from the server side, next to the LISTEN line of the server.

6. Connect to a closed port

Nothing listens on port 8001. Write refused.py. It catches the error that Python raises when the answer is a reset.

refused.py

import socket

try:
    socket.create_connection(("127.0.0.1", 8001), timeout=3)
except ConnectionRefusedError as e:
    print("refused:", e)
python3 refused.py
refused: [Errno 111] Connection refused

The kernel sent a reset at once. curl is a program that transfers a URL. It reports the same fact. -s hides the progress meter, -S still shows an error, and -o /dev/null throws the body away.

curl -sS -o /dev/null http://127.0.0.1:8001/
curl: (7) Failed to connect to 127.0.0.1 port 8001 after 0 ms: Could not connect to server

7. See that UDP does not care

UDP has no handshake, so a sender gets no error when nobody listens. SOCK_DGRAM means a UDP socket, and sendto sends one packet.

python3 -c "
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
print(s.sendto(b'hello', ('127.0.0.1', 8002)), 'bytes sent, no error')
"
5 bytes sent, no error

8. See a connection close

A TCP connection also ends with an exchange: a side sends a FIN ("I have no more data"). The side that closes first keeps a record of the connection for about a minute, in the state TIME-WAIT, so that late packets of the old connection are not mixed with a new one. This program reads until the server stops (recv then gives an empty answer) and closes. sport = :8000 selects the connections whose local port is 8000.

python3 -c "
import socket
s = socket.create_connection(('127.0.0.1', 8000))
s.sendall(b'GET / HTTP/1.0\r\n\r\n')
while s.recv(4096):
    pass
s.close()
"
ss -tn state time-wait sport = :8000
Recv-Q Send-Q Local Address:Port  Peer Address:Port
0      0          127.0.0.1:8000    127.0.0.1:44198

The server closed first, so it holds the record. You may see more than one line: every connection that the server closed in the last minute is listed. The entry is normal and disappears by itself.

9. Stop the server

Press Ctrl+C in the first terminal. Run ss -tlnp | grep 8000 again: it prints nothing, so the port is free.

Your turn

Do the audit of your colleague. There are no steps here: use what you learned about socket and refused connections, on different ports.

Save the program below as three.py and start it in one terminal. It starts three services on 127.0.0.1. Each service sends one line of text (its banner) to every client and closes the connection. Each service runs in its own thread, a second flow of the program, so that three servers work together. server.accept() waits for a client and gives back the connection. daemon=True lets the program end when the main thread ends. The last line, threading.Event().wait(), waits for ever, so the main thread keeps the program alive. Leave it running.

three.py

import socket
import threading

BANNERS = {8041: b"KR-ALPHA\n", 8044: b"KR-BETA\n", 8047: b"KR-GAMMA\n"}


def serve(port, banner):
    server = socket.create_server(("127.0.0.1", port))
    while True:
        conn, _ = server.accept()
        conn.sendall(banner)
        conn.close()


for port, banner in BANNERS.items():
    threading.Thread(target=serve, args=(port, banner), daemon=True).start()
print("three services are up on 127.0.0.1. Press Ctrl+C to stop.", flush=True)
threading.Event().wait()

Do not read the dictionary at the top to get your answers: act as the auditor who does not know it. In a second terminal, write a small Python program that tries every port from 8040 to 8049, prints which ones accept a connection, and prints the banner of each open port. Use ss once to compare with your result. Then answer.

A model scanner
import socket

for port in range(8040, 8050):
    try:
        with socket.create_connection(("127.0.0.1", port), timeout=1) as s:
            print(port, s.recv(100).decode().strip())
    except OSError:
        pass

A closed port raises ConnectionRefusedError, which is a kind of OSError, so the loop skips it. The output has three lines: 8041 KR-ALPHA, 8044 KR-BETA and 8047 KR-GAMMA.

Stop three.py with Ctrl+C, and check with ss -tln that the ports are free.

Check yourself

A scan shows port 22 "refused" on host A and "timed out" on host B. What do you learn?

On host A, the machine is reachable and answers, but nothing listens on port 22. On host B, packets are lost or dropped: a firewall, a wrong route, or a host that is down. Both facts are useful, and they point to different fixes.

Why does the client side of a connection use a port like 35696 that you did not choose?

Every connection needs two ends with a port each. The server's port is fixed so that clients can find it. The client's port only needs to be unique for that conversation, so the kernel picks a free one. This lets one client open many connections to the same server port.

Why can a UDP sender not know if its packet arrived?

UDP has no handshake and no acknowledgement. The kernel sends the packet and forgets it. If the application needs to know, it must build its own answer message and its own retry logic.

In "ss -tlnp" what does the local address 127.0.0.1:8000 tell you about who can connect?

Only programs on this machine. The server accepts connections that arrive on the loopback address only. Lesson 11 shows what changes when the address is 0.0.0.0.

Field notes

  • Make ss -tulnp your first command on an unknown server. -u adds UDP. Compare the list with what should run, and look at the owner of each process. An unexpected listener is a finding.
  • A listener has two parts that matter: the port and the bind address. 127.0.0.1:5432 for a database is a normal local-only setting; 0.0.0.0:5432 exposes it to every network the host is on.
  • Thousands of TIME-WAIT entries are normal on a busy server. Thousands of SYN-RECV connections for one port can mean a SYN flood. Thousands of ESTABLISHED connections from one address can mean a scan or an abuse.
  • ss works from the kernel's own tables, so it is fast. For a list of connections of one process, ss -tnp and the folder /proc/<pid>/fd give the same facts a different way.
  • Port numbers are conventions kept by IANA, not laws. A malicious program can listen on port 443 and a web server can use port 8443. Identify a service by what it says, not by its number.