diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index ddf1ea8..2eda8cc 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -11,80 +11,22 @@ jobs:
qa:
runs-on: ubuntu-latest
timeout-minutes: 15
-
steps:
- name: Check out repository
uses: actions/checkout@v4
-
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.11'
cache: 'pip'
-
- - name: Show tool versions
- run: |
- python --version
- pip --version
- bash --version | head -n 1
-
- - name: Normalise executable permissions from manifest
- run: bash 00_TOOLS/qa/apply_permissions.sh
-
- - name: Check executable permissions
- run: bash 00_TOOLS/qa/check_executability.sh
-
- - name: Run Markdown link checker
- run: python 00_TOOLS/qa/check_markdown_links.py
-
- - name: Run language & lexical integrity check (teaching corpus)
- run: |
- python - <<'PY'
- from pathlib import Path
- import shutil
- import subprocess
- import sys
- import tempfile
-
- src = Path('.').resolve()
- ignored_names = {
- '.git',
- '.github',
- '__pycache__',
- '.pytest_cache',
- '.mypy_cache',
- 'node_modules',
- '.venv',
- 'venv',
- }
-
- with tempfile.TemporaryDirectory(prefix='compnet-integrity-') as td:
- dst = Path(td) / 'repo'
-
- def ignore(path, names):
- ignored = {name for name in names if name in ignored_names}
- if Path(path).resolve() == src:
- ignored.add('CHANGELOG.md')
- return ignored
-
- shutil.copytree(src, dst, ignore=ignore)
- subprocess.run([sys.executable, '00_TOOLS/qa/check_integrity.py'], cwd=dst, check=True)
-
- print('Integrity check passed on teaching corpus (root CHANGELOG.md intentionally excluded as an audit delta document).')
- PY
-
- - name: Validate lecture figure targets
- run: python 00_TOOLS/qa/check_fig_targets.py --puml-only
-
- - name: Run pytest (if present)
- shell: bash
- run: |
- set -euo pipefail
-
- if find . -type f \( -name 'test_*.py' -o -name '*_test.py' \) -print -quit | grep -q .; then
- python -m pip install --upgrade pip
- python -m pip install 'pytest<9' pyyaml
- PYTEST_DISABLE_PLUGIN_AUTOLOAD=1 python -m pytest -q
- else
- echo 'No pytest tests detected, skipping.'
- fi
+ cache-dependency-path: |
+ 00_TOOLS/qa/requirements.txt
+ 03_LECTURES/tests/requirements.txt
+ - name: Set up Node for HTML control-logic tests
+ uses: actions/setup-node@v4
+ with:
+ node-version: '24'
+ - name: Install QA dependencies
+ run: python -m pip install -r 00_TOOLS/qa/requirements.txt
+ - name: Check source and component regressions
+ run: python 00_TOOLS/qa/run_checks.py
diff --git a/.gitignore b/.gitignore
index c497e50..afe3b59 100644
--- a/.gitignore
+++ b/.gitignore
@@ -30,3 +30,8 @@ build/
# Large binaries fetched later
00_TOOLS/plantuml.jar
+
+# Local formative assessment results (keep the documentation).
+00_APPENDIX/a)PYTHON_self_study_guide/formative/results/quiz_results_*.json
+
+.venv-qa/
diff --git a/00_APPENDIX/LIVE_CODING_INSTRUCTOR_GUIDE.md b/00_APPENDIX/LIVE_CODING_INSTRUCTOR_GUIDE.md
index 57f643a..b5230d7 100644
--- a/00_APPENDIX/LIVE_CODING_INSTRUCTOR_GUIDE.md
+++ b/00_APPENDIX/LIVE_CODING_INSTRUCTOR_GUIDE.md
@@ -16,7 +16,7 @@ Live coding is a teaching technique where the instructor **writes code in real t
---
-## 2. Session Structure (15-20 minutess)
+## 2. Session Structure (15-20 minutes)
```
┌─────────────────────────────────────────────────────────────────────────────┐
@@ -134,13 +134,20 @@ sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# STEP 1: "Let's see if Docker responds"
import subprocess
-# QUESTION: "What command checks if Docker is running?"
-result = subprocess.run(['docker', '--version'], capture_output=True, text=True)
-print(f"Docker version: {result.stdout.strip()}")
-
-# PLANNED MISTAKE: Run without sudo service docker start
-# "Cannot connect to Docker daemon"
-# "What do we need to do after restarting Windows?"
+# QUESTION: "Which command contacts the Docker daemon rather than only the CLI?"
+try:
+ result = subprocess.run(['docker', 'info'], capture_output=True, text=True, timeout=15)
+ print("Daemon accessible" if result.returncode == 0 else "Daemon inaccessible")
+ if result.returncode:
+ print(result.stderr.strip())
+except FileNotFoundError:
+ print("Docker CLI is not installed")
+except subprocess.TimeoutExpired:
+ print("Docker daemon check timed out")
+
+# PLANNED MISTAKE: use an explicitly manual-start WSL setup with Docker stopped.
+# A systemd-enabled distribution or Docker Desktop may start its daemon automatically.
+# Inspect docker context, service state and access permissions before changing them.
# STEP 2: "Let's run a simple container"
# QUESTION: "What does 'docker run --rm' do?"
@@ -164,8 +171,10 @@ def check_port(host, port):
return False
# QUESTION: "What port does Portainer listen on?"
-portainer_ok = check_port('localhost', 9000)
-print(f"Portainer accessible: {portainer_ok}")
+portainer_ok = check_port('localhost', 9050)
+print(f"TCP listener on the configured Portainer port: {portainer_ok}")
+# A TCP connection does not establish HTTP readiness or successful authentication.
+# Open the configured URL and verify the Portainer page separately.
# RECAP
# "We verified: Docker installed, daemon running, container functional, Portainer up"
@@ -265,7 +274,7 @@ server.listen(1)
- "What happens if the client disconnects?"
### Questions requiring postponement:
-- "How does TLS work?" → "Excelslow question! We'll cover it in Week 10."
+- "How does TLS work?" → "Excellent question! We'll cover it in Week 10."
### Off-topic questions:
- "Can we do this in Rust?" → "Interesting, but let's focus on Python now. We'll chat at break."
@@ -313,7 +322,7 @@ server.listen(1)
### Before next session
- [ ] Have I published code for students?
-- [ ] Have I updatad slides with clarifications?
+- [ ] Have I updated slides with clarifications?
- [ ] Have I prepared supplementary exercises for difficult concepts?
- [ ] Have I reviewed timing (too fast / too slow)?
@@ -339,7 +348,7 @@ server.listen(1)
### "A student asks questions continuously and derails the course"
```
-- "Excelslow question, but let's discuss at break to not lose the thread"
+- "Excellent question, but let's discuss at break to not lose the thread"
- Visibly note the question on the board
- Return to it if relevant later
```
diff --git a/00_APPENDIX/Makefile b/00_APPENDIX/Makefile
index 5081e9f..7e0a6e3 100644
--- a/00_APPENDIX/Makefile
+++ b/00_APPENDIX/Makefile
@@ -11,12 +11,12 @@
# make export - Export quiz to all formats
# make clean - Clean generated files
-.PHONY: help quiz test lint validate export clean verify all
+.PHONY: help quiz quiz-review quiz-random quiz-validate test test-verbose test-exports test-all lint lint-fix validate validate-python validate-yaml validate-json export export-json export-moodle export-qti clean verify all
# Configuration
PYTHON := python3
QUIZ_DIR := formative
-EXAMPLES_DIR := PYTHON_self_study_guide/examples
+EXAMPLES_DIR := a)PYTHON_self_study_guide/examples
TESTS_DIR := $(EXAMPLES_DIR)/tests
# Colours for output
@@ -90,20 +90,20 @@ quiz-validate:
test:
@echo "$(CYAN)Running smoke tests...$(NC)"
- @$(PYTHON) $(TESTS_DIR)/test_smoke.py
+ @$(PYTHON) "$(TESTS_DIR)/test_smoke.py"
@echo "$(GREEN)✓ Smoke tests passed$(NC)"
test-verbose:
@echo "$(CYAN)Running smoke tests (verbose)...$(NC)"
- @$(PYTHON) -m pytest $(TESTS_DIR)/test_smoke.py -v 2>/dev/null || $(PYTHON) $(TESTS_DIR)/test_smoke.py
+ @$(PYTHON) -m pytest "$(TESTS_DIR)/test_smoke.py" -v
test-exports:
@echo "$(CYAN)Running export function tests...$(NC)"
@if [ -f "$(QUIZ_DIR)/tests/test_quiz_exports.py" ]; then \
- $(PYTHON) $(QUIZ_DIR)/tests/test_quiz_exports.py; \
+ $(PYTHON) $(QUIZ_DIR)/tests/test_quiz_exports.py || exit $$?; \
echo "$(GREEN)✓ Export tests passed$(NC)"; \
else \
- echo "$(YELLOW)⚠ Export tests not found$(NC)"; \
+ echo "$(RED)Export tests not found$(NC)"; exit 1; \
fi
test-all: test test-exports
@@ -116,19 +116,19 @@ test-all: test test-exports
lint:
@echo "$(CYAN)Running linter...$(NC)"
@if command -v ruff >/dev/null 2>&1; then \
- ruff check $(EXAMPLES_DIR)/*.py $(QUIZ_DIR)/*.py --ignore E501; \
+ ruff check "$(EXAMPLES_DIR)"/*.py $(QUIZ_DIR)/*.py --ignore E501; \
elif command -v flake8 >/dev/null 2>&1; then \
- flake8 $(EXAMPLES_DIR)/*.py $(QUIZ_DIR)/*.py --max-line-length=120; \
+ flake8 "$(EXAMPLES_DIR)"/*.py $(QUIZ_DIR)/*.py --max-line-length=120; \
else \
echo "$(YELLOW)⚠ No linter found. Install with: pip install ruff$(NC)"; \
- $(PYTHON) -m py_compile $(EXAMPLES_DIR)/*.py $(QUIZ_DIR)/*.py; \
+ $(PYTHON) -m py_compile "$(EXAMPLES_DIR)"/*.py $(QUIZ_DIR)/*.py || exit $$?; \
echo "$(GREEN)✓ Syntax check passed$(NC)"; \
fi
lint-fix:
@echo "$(CYAN)Running linter with auto-fix...$(NC)"
@if command -v ruff >/dev/null 2>&1; then \
- ruff check $(EXAMPLES_DIR)/*.py $(QUIZ_DIR)/*.py --fix --ignore E501; \
+ ruff check "$(EXAMPLES_DIR)"/*.py $(QUIZ_DIR)/*.py --fix --ignore E501; \
else \
echo "$(YELLOW)⚠ ruff not found. Install with: pip install ruff$(NC)"; \
fi
@@ -142,7 +142,7 @@ validate: validate-python validate-yaml validate-json
validate-python:
@echo "$(CYAN)Validating Python syntax...$(NC)"
- @find . -name "*.py" -type f -exec $(PYTHON) -m py_compile {} \;
+ @$(PYTHON) -m compileall -q .
@echo "$(GREEN)✓ Python syntax valid$(NC)"
validate-yaml:
@@ -153,7 +153,7 @@ validate-yaml:
validate-json:
@echo "$(CYAN)Validating JSON files...$(NC)"
@if [ -f "$(QUIZ_DIR)/quiz.json" ]; then \
- $(PYTHON) -c "import json; json.load(open('$(QUIZ_DIR)/quiz.json'))"; \
+ $(PYTHON) -c "import json; json.load(open('$(QUIZ_DIR)/quiz.json'))" || exit $$?; \
echo "$(GREEN)✓ JSON valid$(NC)"; \
else \
echo "$(YELLOW)⚠ quiz.json not found (optional)$(NC)"; \
@@ -163,7 +163,7 @@ validate-json:
# EXPORT TARGETS
#═══════════════════════════════════════════════════════════════════════════════
-export: export-json export-moodle
+export: export-json export-moodle export-qti
@echo "$(GREEN)✓ All exports completed$(NC)"
export-json:
@@ -204,7 +204,7 @@ clean:
@find . -type f -name "*.pyc" -delete 2>/dev/null || true
@find . -type f -name "*_export.json" -delete 2>/dev/null || true
@find . -type f -name "*_moodle.gift" -delete 2>/dev/null || true
- @find . -type f -name "*_qti.xml" -delete 2>/dev/null || true
+ @find . -type f \( -name "*_qti.xml" -o -name "*_qti.zip" \) -delete 2>/dev/null || true
@echo "$(GREEN)✓ Clean completed$(NC)"
#═══════════════════════════════════════════════════════════════════════════════
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/CANONICAL_LAB_MAP.md b/00_APPENDIX/a)PYTHON_self_study_guide/CANONICAL_LAB_MAP.md
new file mode 100644
index 0000000..d1afaac
--- /dev/null
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/CANONICAL_LAB_MAP.md
@@ -0,0 +1,62 @@
+# Python self-study: canonical COMPNET-EN paths
+
+Use this map with the [Python guide](PYTHON_NETWORKING_GUIDE.md) and its ten HTML
+modules. Run terminal commands from the **repository root inside the Linux VM or
+selected WSL environment**. A slide's Simulate/Show output control displays a
+prepared teaching illustration; it does not execute Python or generate a capture.
+
+| Module | Real source or entry point | What to inspect or run |
+|---|---|---|
+| 1–2: setup and reading | [05_ping_latency.py](examples/05_ping_latency.py) | Dataclass, argparse, subprocess result and bounded failure handling |
+| 3: bytes and text | [02_bytes_vs_str.py](examples/02_bytes_vs_str.py) | Encoding, decoding and temporary-file ownership |
+| 4: sockets | [01_socket_tcp.py](examples/01_socket_tcp.py), [S02](../../04_SEMINARS/S02/) | Separate server/client processes and the actual protocol handout |
+| 5: organisation | [03_struct_parsing.py](examples/03_struct_parsing.py) | Importable functions, IPHeader dataclass and main guard |
+| 6: CLI | [05_ping_latency.py](examples/05_ping_latency.py), [lab runner](../../00_TOOLS/lab_runner/) | The actual --help and documented arguments |
+| 7: packet analysis | [S07](../../04_SEMINARS/S07/), [PCAP tools](../../00_TOOLS/pcap/) | Capture privileges, interfaces and parsed fields |
+| 8: concurrency | [S03 multi-client server](../../04_SEMINARS/S03/S03_Part01_Example_TCP_Multi_client_Server.py) | Client lifetime, framing and concurrency |
+| 9: HTTP | [S08](../../04_SEMINARS/S08/), [C10 scenarios](../../03_LECTURES/C10/) | HTTP framing, request/response bytes and proxy behaviour |
+| 10: debugging | [04_error_handling.py](examples/04_error_handling.py), [tests](examples/tests/) | Resource ownership, errors and component regression evidence |
+
+## First runnable checks
+
+```bash
+cd "$HOME/COMPNET-EN"
+python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/05_ping_latency.py" --host 127.0.0.1 --count 3
+python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/02_bytes_vs_str.py"
+python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/03_struct_parsing.py"
+```
+
+The ping helper needs Linux `ping` (iputils-ping). A missing command, unsuccessful
+reply or unparsed RTT produces a non-zero exit. Report those observations rather
+than substituting the slide's example timings.
+
+For the socket example, use two Linux terminals in the repository root:
+
+```bash
+# Terminal A: stop with Ctrl+C after the experiment.
+python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/01_socket_tcp.py" server 9090
+```
+
+```bash
+# Terminal B
+python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/01_socket_tcp.py" client 127.0.0.1 9090 "Test"
+```
+
+For subnetting, the C05 calculator accepts a positional address/prefix:
+
+```bash
+python3 03_LECTURES/C05/assets/scenario-cidr-basic/cidr-calc.py 192.168.23.233/24
+```
+
+Do not assume every course script implements argparse or a common `--mode` option.
+The S04 text framing, binary framing and pickle-based UDP exercise are defined by
+[S04's source and handouts](../../04_SEMINARS/S04/). Generic JSON, checksum and package
+sketches in this Python guide are separate learning examples.
+
+## Provenance
+
+Earlier versions of these optional materials referred to the external netROwsl kit.
+The v1.5.0 revision maps learning activities to COMPNET-EN while retaining the Python
+concepts. Repository v1.4.0 preserves the prior text. The VM remains
+[MININET-SDN 1.0.0](https://doi.org/10.5281/zenodo.24289763); see
+[environment routes](../docs/environment_routes.md) for installation and Portainer.
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/Makefile b/00_APPENDIX/a)PYTHON_self_study_guide/Makefile
index 0318dfe..b689e4b 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/Makefile
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/Makefile
@@ -25,7 +25,7 @@
.DEFAULT_GOAL := help
# Python interpreter
-PYTHON := python3
+PYTHON := $(if $(wildcard .venv/bin/python),.venv/bin/python,python3)
# Directories
QUIZ_DIR := formative
@@ -224,14 +224,7 @@ test: test-all
test-all:
@echo "$(COLOUR_BOLD)Running all tests...$(COLOUR_RESET)"
- @if command -v pytest >/dev/null 2>&1; then \
- pytest $(TESTS_DIR)/ -v; \
- else \
- $(PYTHON) -m pytest $(TESTS_DIR)/ -v 2>/dev/null || \
- ($(PYTHON) $(TESTS_DIR)/test_smoke.py && \
- $(PYTHON) $(TESTS_DIR)/test_bytes_vs_str.py && \
- $(PYTHON) $(TESTS_DIR)/test_struct_parsing.py); \
- fi
+ @$(PYTHON) -m pytest $(TESTS_DIR)/ -v
test-smoke:
@echo "$(COLOUR_BOLD)Running smoke tests...$(COLOUR_RESET)"
@@ -270,10 +263,11 @@ check:
@echo "$(COLOUR_GREEN)Environment check complete.$(COLOUR_RESET)"
install:
- @echo "$(COLOUR_BOLD)Installing dependencies...$(COLOUR_RESET)"
- @pip install --user pyyaml pytest 2>/dev/null || \
- pip install pyyaml pytest --break-system-packages || \
- echo "$(COLOUR_YELLOW)Please install: pip install pyyaml pytest$(COLOUR_RESET)"
+ @echo "Creating a local virtual environment for this guide..."
+ @python3 -m venv .venv
+ @.venv/bin/python -m pip install 'PyYAML==6.0.3' 'pytest==8.4.2'
+ @echo "Done. Make targets now use .venv/bin/python; activate it with: source .venv/bin/activate"
+
lint:
@echo "$(COLOUR_BOLD)Checking code style...$(COLOUR_RESET)"
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/01_introduction_setup.html b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/01_introduction_setup.html
index c79a7a2..e3290d7 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/01_introduction_setup.html
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/01_introduction_setup.html
@@ -809,7 +809,11 @@
margin-bottom: 1rem;
animation: pulse 2s infinite;
}
-
+ button.quiz-option {width:100%;color:inherit;font:inherit;text-align:left;}
+button.quiz-option:focus-visible,.page-dot:focus-visible {outline:3px solid var(--accent-primary);outline-offset:3px;}
+button.page-dot {border:0;padding:0;}
+code,.file-name {overflow-wrap:anywhere;}
+
@@ -833,6 +837,7 @@
+
Interactive outputs are prewritten demonstrations. Run the canonical scripts in the VM or supported Linux environment using the lab map.
🐍
Python for Networks
Interactive Self-Study Guide
@@ -879,8 +884,8 @@
🎯 What will we learn in this module?
💻
- WSL2 Working Environment
- How WSL2 + Ubuntu + Docker + Portainer work together and why we use them
+ Linux working environment
+ How the VM and separate WSL routes relate and why we use them
@@ -901,74 +906,20 @@
💡 Why it matters?
-
-
-
📂 Repository Structure netROwsl
-
-
The repository at github.com/antonioclim/netROwsl contains all lab materials. Each week has its own folder following a consistent structure:
-
-
-
-
- 📁
- netROwsl/
-
-
- 📁
- 01roWSL/
- ← Wk 1
-
-
- 📁
- src/exercises/
-
-
- 🐍
- ex_1_01_latency_ping.py
-
-
- 📁
- docker/
-
-
- 📁
- docs/
-
-
- 📁
- 02roWSL/
- ← Wk 2
-
-
- ...
-
-
- 📁
- 14roWSL/
- ← Wk 14
-
-
-
-
-
-
📍 Key Folders
-
src/exercises/ - Main exercises with TODOs
-
src/apps/ - Complete demonstration applications
-
src/utils/ - Reusable helper functions
-
docker/ - Container configurations
-
tests/ - Automated tests
-
-
-
-
⚠️ Warning
-
Files in exercises/ contain TODO sections for you to complete. Do not modify files in apps/ — those are reference examples!
-
-
-
-
-
+
+
Repository structure: COMPNET-EN
+
The course has separate entry points for lectures, seminars, projects and optional Python practice. Start with the README of the selected unit.
+
Path from repository root
Purpose
+
03_LECTURES/C01/ … C14/
Lecture notes, diagrams and executable scenarios
+
04_SEMINARS/S01/ … S14/
Student explanations, tasks, examples and templates
+
02_PROJECTS/
Project requirements and evidence criteria
+
00_TOOLS/
Shared setup, capture and validation tools
+
00_APPENDIX/a)PYTHON_self_study_guide/
This optional guide, examples and formative practice
+
+
Files labelled Example are references; Template files identify student completion work. Read each task's contract before changing a template.
Debugging Debugging & Best practices Best practices
+
Debugging and best practices
@@ -1052,60 +1003,17 @@
💡 Tip
-
-
-
🖥️ Working Environment: WSL2 + Docker
-
-
The lab sessions employ a modern technology stack for network simulation:
-
-
-
-
🪟 WSL2 (Windows Subsystem for Linux)
-
What it is: A real Linux kernel running in Windows
-
Why: Networking tools (Wireshark, tcpdump) work natively
-
Access: Open "Ubuntu" from Start Menu or type wsl in PowerShell
-
-
-
-
🐳 Docker
-
What it is: Isolated containers for simulating network servers and services
-
Why: You can run DNS, HTTP, FTP servers without installing them on the system
-
Start:sudo service docker start
-
-
-
-
🎛️ Portainer
-
What it is: Web interface for managing Docker containers
-
Why: Easily visualise running containers and inspect their logs
-
Access:http://localhost:9000
-
+
+
Choose the installed environment
+
The primary course route uses the working MININET-SDN VirtualBox appliance. Run Linux commands in the guest, normally through SSH on Windows loopback port 2222. The WSL2 route is a separately documented alternative.
+
VM or native WSL Engine
Docker and Python run inside the selected Linux environment. docker info checks daemon access; docker --version checks only the client.
Optional Portainer
The course setup maps host loopback 9050 to container HTTP 9000. Access from Windows into the VM requires a tunnel or forwarding rule. Existing personal credentials are preserved.
+
python3 --version
+docker context show
+docker info
Think about the folder names. Which folder suggests it contains tasks to complete (exercises)?
+
Seminar folders use S followed by the two-digit week number.
Hint 2/3
@@ -1238,7 +1143,7 @@
Quiz 1: Repository Structure
The correct answer is exercises/ - here you find files with TODOs that you complete during the lab.
-
+
@@ -1255,22 +1160,22 @@
Quiz 2: Working Environment
-
+
-
+
+
-
+
+
-
+
+
+
@@ -1291,7 +1196,7 @@
Quiz 2: Working Environment
Docker enables service isolation through containers. This allows us to simulate an entire network with different servers, each running in its own container.
-
+
@@ -1306,13 +1211,13 @@
✅ Summary and Next Steps
📌 What We Covered
- ✓ The netROwsl repository structure
+ ✓ The COMPNET-EN repository structure
✓ The correlation between Python modules and lab weeks
- ✓ The WSL2 + Docker + Portainer stack
+ ✓ The VM and separate WSL routes
✓ How to run the first Python networking script
@@ -1343,7 +1248,7 @@
Reading Real Exercises
- We will analyse ex_1_01_latency_ping.py line by line together
+ We will analyse 00_APPENDIX/a)PYTHON_self_study_guide/examples/05_ping_latency.py line by line together
@@ -764,11 +769,11 @@
💡 Why it matters?
📄 Anatomy of a Python File
-
Every exercise in the starter kits follows a standard structure. Let us analyse its components:
+
The following excerpt illustrates common Python file structure. Incomplete fragments are for reading; the runnable reference is examples/05_ping_latency.py in this guide.
defanalyse_network(
ip_addresses: List[str], # List of strings
- config: Dict[str, int], # Dictionaryy str→int
+ config: Dict[str, int], # Dictionary str→int
timeout: Optional[float] = None# Float or None
) -> Tuple[int, List[str]]: # Returns a tuple"""Analyses a list of IP addresses."""
@@ -951,7 +956,7 @@
📐 Type Hints — Documenting Types
⚠️ Important
-
Type hints serve only as documentation — Python does NOT enforce them at runtime. You can pass any type and the code will still run. Tools such as mypy perform static checking.
+
Type hints serve only as documentation — Python does NOT enforce them at runtime. A wrong type may still fail when an operation uses it; annotations alone do not enforce the contract. Tools such as mypy perform static checking.
@@ -1054,13 +1059,13 @@
🔑 The Essential Difference
-
🔍 Analysing Real Code: ex_1_01_latency_ping.py
+
🔍 Analysing Real Code: 00_APPENDIX/a)PYTHON_self_study_guide/examples/05_ping_latency.py
-
Let us analyse a real fragment from the Week 1 exercise:
+
This shortened reading exercise illustrates subprocess and dataclass use. The complete implementation is in the canonical ping helper:
🎯 Purpose: Verify that your modification took effect
👀 What you will see: It now sends 5 packets instead of 3
@@ -1205,22 +1210,22 @@
Quiz 1: Dataclasses
-
+
-
+
+
-
+
+
-
+
+
+
@@ -1241,7 +1246,7 @@
Quiz 1: Dataclasses
@dataclass = "data class" = a class designed for holding data. It automatically generates a constructor (__init__), a text representation (__repr__) and equality comparisons (__eq__).
-
+
@@ -1263,22 +1268,22 @@
Quiz 2: Type Hints
-
+
-
+
+
-
+
+
-
+
+
+
@@ -1299,7 +1304,7 @@
Quiz 2: Type Hints
If the ping fails, there is no valid RTT. Instead of using a magic value (-1), we use None to indicate "no value".
-
+
@@ -1316,22 +1321,22 @@
Quiz 3: Python Syntax
-
+
-
+
+
-
+
+
-
+
+
+
@@ -1352,7 +1357,7 @@
Quiz 3: Python Syntax
The code block is delimited by indentation (spaces) rather than curly braces. The for line ends with :
-
+
@@ -1368,7 +1373,7 @@
💻 Sandbox: Experiment with the Code
🐍 sandbox_dataclass.py
-
+
@@ -1484,7 +1489,7 @@
🚀 Next Module
🌐
Practical Application in the Lab
-
You can now open any exercise from 01roWSL or 02roWSL and understand its structure. Identify the dataclasses used to represent packets, ping results and connections.
+
You can now open any exercise from 04_SEMINARS/S01 or 04_SEMINARS/S02 and understand its structure. Identify the dataclasses used to represent packets, ping results and connections.
Interactive outputs are prewritten demonstrations. Run the canonical scripts in the VM or supported Linux environment using the lab map.
🔤
Data Types for Networking
bytes vs str — The Critical Distinction
@@ -200,7 +205,7 @@
🎯 What will we learn in this module?
🌐
Applications in Networking
- How these concepts are used in the actual exercises from 02roWSL and 03roWSL
+ How these concepts are used in the actual exercises from 04_SEMINARS/S02 and 04_SEMINARS/S03
@@ -268,7 +273,7 @@
🔄 Conversion: encode() and decode()
🐍 conversion_demo.py
-
+
@@ -327,7 +332,7 @@
📦 Bytes Literal — Writing Directly
🐍 bytes_literal.py
-
+
@@ -359,7 +364,7 @@
📦 Bytes Literal — Writing Directly
IP as hex: c0a80101
IP decoded: 192.168.1.1
-Request length: 37 bytes
+Request length: 35 bytes
IP length: 4 bytes
@@ -455,7 +460,7 @@
📋 List Comprehensions — Compact Processing
🐍 comprehensions_networking.py
-
+
@@ -513,7 +518,7 @@
📚 Dict Comprehensions — Parsing Headers
🐍 dict_comprehension_http.py
-
+
@@ -566,7 +571,7 @@
📚 Dict Comprehensions — Parsing Headers
🌐
Where will you use this?
-
In 08roWSL/src/exercises/ex_8_01_server_http.py you will need to parse exactly this kind of headers!
+
In 04_SEMINARS/S08/3_socket-http/S08_Part03B_Example_Socket_HTTP_Server.py you will need to parse exactly this kind of headers!
@@ -580,7 +585,7 @@
🧪 Experiment: bytes in a Real Exercise
🔬
- Explore Conversion in ex_2_01_tcp.py
+ Explore Conversion in 00_APPENDIX/a)PYTHON_self_study_guide/examples/01_socket_tcp.py
Interactive outputs are prewritten demonstrations. Run the canonical scripts in the VM or supported Linux environment using the lab map.
📁
Code Organisation
Functions, Modules and Project Structure
@@ -168,7 +173,7 @@
🎯 What will we learn?
🏗️
-
Project StructureHow exercises are organised in netROwsl
+
Project StructureHow exercises are organised in COMPNET-EN
@@ -184,7 +189,8 @@
📦 Functions in Python
# Simple functiondefcalculate_checksum(data: bytes) -> int:
"""
- Calculate the checksum of a packet.
+ Calculate a simplified 16-bit complement of the word sum.
+ This teaching function is not the RFC 1071 Internet checksum: no end-around carry.
Args:
data: Packet data as bytes
@@ -232,7 +238,7 @@
📂 Modules and Imports
network.py
parsers.py
📁 exercises/
-
ex_4_01.py
+
frame_exercise.py
🐍 Import types
@@ -257,33 +263,12 @@
📂 Modules and Imports
-
-
-
🏗️ netROwsl Project Structure
-
-
-
04roWSL/
-
📁 src/
-
📁 exercises/
-
📁 apps/
-
📁 utils/
-
📁 docker/
-
📁 scripts/
-
start_lab.py
-
📁 tests/
-
README.md
-
-
-
exercises/
Files with TODO placeholders that you complete
-
apps/
Complete reference applications (do not modify)
-
utils/
Reusable helper functions that you import
-
scripts/
Orchestration: lab startup and traffic captures
-
-
-
-
+
+
COMPNET-EN organisation
Canonical course files live in 03_LECTURES, 04_SEMINARS, 02_PROJECTS and 00_TOOLS. This guide keeps small standalone examples in its own examples/ directory.
+
The src/utils/ tree shown in the preceding slide is an illustrative package design you could create in your own project. It is not a required directory in every course unit.
Use each unit's README to find scripts, configurations, tasks and dependencies. Templates and complete examples are labelled separately.
The first and third programs use argparse; the CIDR calculator accepts a positional address/prefix. Read each actual interface instead of assuming a common --mode or --host option.
Interactive outputs are prewritten demonstrations. Run the canonical scripts in the VM or supported Linux environment using the lab map.
🔧
Debugging and Best Practices
Quality Code for Networks
@@ -72,7 +77,7 @@
🎯 What Will We Learn?
📝 Logging — Stop Using print()!
-
🐍 proper_logging.py
+
🐍 proper_logging.py
import logging
@@ -198,6 +203,7 @@
⚠️ Error Handling for Networking
🧪 Testing with pytest
+
This is an illustrative test module for a hypothetical utils.network package. For tests of the actual repository examples, run python3 -m pytest "00_APPENDIX/a)PYTHON_self_study_guide/examples/tests" from the repository root after installing the QA requirements.
🐍 test_network_utils.py
@@ -390,10 +396,10 @@
📝 Quiz
Which logging level is correct for "connection lost"?
-
ADEBUG
-
BINFO
-
CWARNING
-
DCRITICAL
+
+
+
+
@@ -402,7 +408,7 @@
📝 Quiz
Hint 1/3
A lost connection is unexpected, but the server can continue.
Hint 2/3
It is not fatal (CRITICAL), but not normal (INFO) either.
Hint 3/3
WARNING = something suspicious, but the application continues running.
-
+
@@ -416,10 +422,10 @@
📝 Quiz
What tool do you use to view packets on the network?
-
Apdb
-
Btcpdump / Wireshark
-
Cpytest
-
Dblack
+
+
+
+
@@ -428,7 +434,7 @@
📝 Quiz
Hint 1/3
pdb is for Python. pytest is for tests. black is for formatting.
Hint 2/3
Wireshark has a GUI; tcpdump is CLI-based.
Hint 3/3
tcpdump and Wireshark are packet sniffers for network analysis.
-
+
@@ -478,7 +484,7 @@
📜 Summary: 10 Modules Complet
🚀
Next Steps
-
Continue with exercises from the netROwsl repository. Each week has TODOs that consolidate what you have covered!
+
Continue with exercises from the COMPNET-EN repository. Each week has TODOs that consolidate what you have covered!
Safe means the method does not alter server state — a proxy may pre-fetch safe resources. Idempotent means repeating the request produces the same final state — load balancers and retry logic depend on this. Cacheable means intermediaries may store and reuse the response without contacting the server.
+
Safe means the client does not request a state-changing effect (logging may still occur) — a proxy may pre-fetch safe resources. Idempotent means repeating the request produces the same final state — load balancers and retry logic depend on this. Cacheable means intermediaries may store and reuse the response without contacting the server.
@@ -615,10 +615,10 @@
Checkpoint — Status Code Diagnostics
C) The user is authenticated but lacks permission to delete this resource.
D) The server does not support the DELETE method.
-
Correct. 403 Forbidden means the server understood the request and recognised the caller, but the caller does not have authorisation for this specific action. The distinction: 401 = who are you? (authentication missing), 403 = I know who you are, but you may not do this (authorisation denied).
-
An expired or malformed token would produce 401 Unauthorized, not 403. The 401 code signals that authentication is missing or invalid. A 403 presupposes that authentication succeeded but the caller lacks permission.
-
A non-existent resource would produce 404 Not Found. The server returns 403 specifically to say “the resource exists, you are authenticated, but you lack permission.”
-
If the server did not support DELETE on this endpoint, it would return 405 Method Not Allowed, typically with an Allow header listing the permitted methods.
+
Correct for the stated valid-token scenario: an authorisation refusal is most likely. In general 403 means the server understood and refuses the request; it does not establish authentication. A 401 challenges missing or invalid credentials.
+
An expired or malformed token would produce 401 Unauthorized, not 403. The 401 code signals that authentication is missing or invalid. For this stated scenario, the valid token makes an authorisation refusal likely; 403 in general does not prove successful authentication.
+
A non-existent resource would produce 404 Not Found. A server can use 404 to avoid disclosing a forbidden resource. Neither status alone proves whether a resource exists.
+
If the server did not support DELETE on this endpoint, it would return 405 Method Not Allowed, with a required Allow header listing the permitted methods.
@@ -750,7 +750,7 @@
CORS: The Browser Security Model
Cross-origin (blocked unless server opts in)
-
https://app.example.com requests https://api.example.com — different host. The browser sends a preflightOPTIONS request to ask permission.
+
https://app.example.com requests https://api.example.com — different host. A non-safelisted method or header causes a preflightOPTIONS request. Safelisted cross-origin requests can be sent without preflight, though the browser still checks CORS response permissions.
@@ -895,12 +895,14 @@
WebSocket: When HTTP Is No Longer Enough
GET /chat HTTP/1.1Upgrade: websocket
Connection: Upgrade
-Sec-WebSocket-Key: dGhlIHNh...
+Sec-WebSocket-Version: 13
+Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==
# Server confirmsHTTP/1.1101Switching ProtocolsUpgrade: websocket
-Connection: Upgrade
An API endpoint POST /api/users/42/activate changes the user’s status to “active”. At which Richardson maturity level does this endpoint operate?
+
An API provides separate resource URIs, but uses POST for every read and write, encodes the operation in an action field and always returns 200. It has no hypermedia links. Which Richardson maturity level best describes it?
-
A) Level 2 — because it uses a URI for the resource and POST for the action.
-
B) Level 1 — it has a resource URI but encodes the action in the URL path instead of using HTTP methods.
-
C) Level 3 — because it targets a specific sub-resource of the user.
-
D) Level 0 — because POST is used instead of GET.
+
A) Level 2 — any use of HTTP methods is sufficient.
+
B) Level 1 — resources have URIs, but HTTP method and status semantics are not used.
+
C) Level 3 — separate URIs automatically provide hypermedia.
+
D) Level 0 — any use of POST implies a single-endpoint API.
+
+
Correct. The description supplies the behaviour needed for Level 1. A URI containing an action word, or one POST endpoint alone, cannot classify an entire API.
+
Level 2 uses HTTP method and status semantics appropriately, which the stated API does not.
+
Level 3 adds response hypermedia that guides clients to available actions.
+
Separate resource URIs distinguish this example from the single-endpoint Level 0 model.
-
Correct. The verb “activate” in the URL is a strong indicator of RPC-style thinking encoded in a resource path. At Level 2, you would model this as PATCH /api/users/42 with a body like {"status": "active"}, using the HTTP method (PATCH) to express the action and the body to express the change. The URL /activate is an action, not a resource.
-
Level 2 requires using HTTP methods to express operations. Here, the action “activate” is baked into the URL path, which means the API is using the URL as a verb rather than letting the HTTP method carry that information. This is characteristic of Level 1.
-
Level 3 (HATEOAS) requires the server to include hypermedia links in responses, guiding the client to available actions. The URL structure alone does not determine Level 3.
-
Level 0 uses a single endpoint for all operations (e.g. POST /api). Here, the API does address a specific resource URI, placing it above Level 0.
curl timing values are cumulative from the request start. Without redirects, approximate TCP setup as time_connect minus time_namelookup and TLS setup as time_appconnect minus time_connect. Redirects and connection reuse require separate interpretation.
At 07:10 EDT, the DNS provider Dyn began receiving an unprecedented flood of traffic — over 1.2 Tbit/s from roughly 100,000 compromised IoT devices. Within minutes, DNS resolution for major websites stopped working. Twitter, Netflix, Reddit, GitHub, Spotify and dozens of other services became unreachable for millions of users across North America and Europe.
+
At 07:10 EDT, the DNS provider Dyn began receiving an unprecedented flood of traffic — from a large botnet of compromised IoT devices. Within minutes, DNS resolution for major websites stopped working. Twitter, Netflix, Reddit, GitHub, Spotify and dozens of other services became unreachable for millions of users across North America and Europe.
The Paradox
@@ -580,13 +580,13 @@
Definition
Protocol Details
Primary transport: UDP port 53
-
TCP for zone transfers and large responses (> 512 bytes)
+
TCP for AXFR and for truncated responses; EDNS permits UDP payloads above the historical 512-byte limit
Specified in RFC 1034/1035 (1987)
Why UDP?
-
DNS queries are typically small (< 512 bytes) and need low latency. A UDP round-trip completes in one request–response exchange. If the response is truncated (the TC flag is set), the client retries over TCP.
+
DNS queries are typically small and benefit from low latency. The original UDP limit was 512 bytes; EDNS negotiates a larger supported UDP payload. A UDP round-trip completes in one request–response exchange. If the response is truncated (the TC flag is set), the client retries over TCP.
@@ -685,7 +685,7 @@
DNS Resolution: Step by Step
Iterative vs Recursive
-
The recursive resolver does the heavy lifting — querying root, TLD and authoritative servers in sequence. The client's stub resolver simply sends one query to the recursive resolver and waits for the final answer. This is why attacking the recursive resolver (as in the Dyn incident) has such catastrophic effects.
+
The recursive resolver does the heavy lifting — querying root, TLD and authoritative servers in sequence. The client's stub resolver simply sends one query to the recursive resolver and waits for the final answer. This is why attacking a critical DNS dependency (the Dyn incident targeted authoritative infrastructure) has such catastrophic effects.
@@ -1255,7 +1255,7 @@
Returning to the Dyn Attack
Now We Can Explain It
-
The Mirai botnet directed 1.2 Tbit/s of traffic at Dyn, a major recursive DNS resolver provider. Because millions of clients depended on Dyn to translate domain names into IP addresses, the attack did not need to touch Twitter, Netflix or GitHub at all.
+
The Mirai botnet contributed to the attack on Dyn, a major authoritative DNS provider. Because millions of clients depended on Dyn to translate domain names into IP addresses, the attack did not need to touch Twitter, Netflix or GitHub at all.
With the resolver overwhelmed, stub resolvers received no answers. Browsers displayed "DNS_PROBE_FINISHED_NXDOMAIN" — the sites appeared to not exist, even though their servers were fully operational.
@@ -1473,15 +1473,15 @@
The Unifying Perspective
Synthesis Question
-
A company's website became unreachable for 45 minutes, but their server logs show zero downtime during this period. The engineering team discovered that their DNS provider experienced an outage. Why did the outage persist for exactly 45 minutes after the provider recovered?
+
During a DNS configuration error, a resolver cached an authoritative NXDOMAIN answer with a 2,700-second negative TTL. The correct record was restored immediately afterwards. Why might that resolver still report NXDOMAIN for almost 45 minutes?
DNS servers take 45 minutes to restart after a crash
TCP connections to DNS servers have a 45-minute timeout
-
Negative responses (NXDOMAIN/SERVFAIL) were cached by resolvers with a TTL that had not yet expired
+
The authoritative NXDOMAIN answer remains in this resolver’s negative cache until its 2,700-second TTL expires
The company's firewall blocked DNS traffic for 45 minutes
-
✓ Correct. During the outage, resolvers received error responses (SERVFAIL or NXDOMAIN) and cached them according to the SOA record's minimum TTL or the resolver's negative caching policy. Even after the DNS provider recovered, these cached negative answers continued to be served until the negative cache TTL expired. This is why DNS TTL configuration matters for both positive and negative responses.
-
✗ The key is negative caching. When DNS resolution fails, resolvers do not simply forget — they cache the failure for a period defined by the SOA minimum TTL. After recovery, these stale "this domain does not exist" answers persist in caches until the negative TTL expires.
+
✓ Correct. RFC 2308 negative caching uses the lower of the SOA TTL and SOA MINIMUM. The stated NXDOMAIN and TTL explain this observation. SERVFAIL is a resolution failure, not proof of nonexistence; RFC 9520 limits resolution-failure caching to five minutes.
+
✗ The question specifies a cached authoritative NXDOMAIN and its TTL. An outage alone would not determine a 45-minute delay, and SERVFAIL must not be interpreted as a nonexistent name.
@@ -1669,6 +1669,7 @@
Reflection and Closing
}
document.addEventListener('keydown', function(e) {
+ if (e.target && e.target.closest && e.target.closest('input, textarea, select, button, [contenteditable="true"]')) return;
switch(e.key) {
case 'ArrowRight': case ' ': nextSlide(); e.preventDefault(); break;
case 'ArrowLeft': prevSlide(); e.preventDefault(); break;
@@ -1774,39 +1775,31 @@
Reflection and Closing
// Interactive: DNS Resolution Simulator
// ═══════════════════════════════════════════
function simulateDNS() {
- var input = document.getElementById('dnsInput');
- var result = document.getElementById('dnsSimResult');
- if (!input || !result) return;
-
- var domain = input.value.trim().toLowerCase();
- if (!domain || domain.indexOf('.') === -1) {
- result.innerHTML = '
Please enter a valid domain name (e.g. www.ase.ro)
';
+ const domain = document.getElementById('dnsInput').value.trim().toLowerCase();
+ const result = document.getElementById('dnsSimResult');
+ result.replaceChildren();
+ if (!/^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z0-9-]{2,63}$/.test(domain)) {
+ result.textContent = 'Enter a DNS name such as www.example.test.';
return;
}
-
- var parts = domain.split('.');
- var tld = '.' + parts[parts.length - 1];
- var sld = parts.length >= 2 ? parts[parts.length - 2] : '';
- var sub = parts.length >= 3 ? parts.slice(0, parts.length - 2).join('.') : '';
- var fakeIP = (Math.floor(Math.random() * 200) + 10) + '.' +
- (Math.floor(Math.random() * 255)) + '.' +
- (Math.floor(Math.random() * 255)) + '.' +
- (Math.floor(Math.random() * 254) + 1);
-
- var steps = [
- '1. Stub resolver queries recursive resolver: "What is the A record for ' + domain + '?"',
- '2. Recursive resolver queries root server: "Who handles ' + tld + '?"',
- ' → Root responds: "Ask ' + tld.slice(1) + '.ns.example (TLD server)"',
- '3. Recursive resolver queries ' + tld + ' TLD server: "Who handles ' + sld + tld + '?"',
- ' → TLD responds: "Ask ns1.' + sld + tld + ' (authoritative)"',
- '4. Recursive resolver queries authoritative server: "What is ' + domain + '?"',
- ' → Authoritative responds: "' + domain + ' = ' + fakeIP + '" (TTL: 3600)',
- '5. Recursive resolver returns answer to client and caches the result.'
+ const parts = domain.split('.');
+ const tld = parts.at(-1);
+ const zone = parts.slice(-2).join('.');
+ const lines = [
+ 'Illustrative simulation only: no DNS lookup is performed.',
+ '1. Stub resolver asks its recursive resolver for ' + domain,
+ '2. With an empty cache, the resolver obtains a referral from the root for .' + tld,
+ '3. A TLD server refers it towards the authoritative servers for ' + zone + ' (simplified delegation).',
+ '4. An authoritative server returns the illustrative A record 192.0.2.42 with TTL 3600.',
+ '5. The resolver caches the answer and returns it to the client.'
];
-
- result.innerHTML = '
Resolving: ' + domain + '
' +
- steps.map(function(s) { return '
' + s + '
'; }).join('');
+ for (const line of lines) {
+ const paragraph = document.createElement('p');
+ paragraph.textContent = line;
+ result.append(paragraph);
+ }
}
+