✓ How to run the first Python networking script
@@ -1343,7 +1248,7 @@ 🚀 Next Module
Additional Resources
-
+
📁
GitHub Repository
@@ -1394,11 +1299,13 @@
🚀 Next Module
// Initialize
document.addEventListener('DOMContentLoaded', () => {
- updataUI();
+ updateUI();
createPageDots();
+ goToSlide(currentSlide);
// Keyboard navigation
document.addEventListener('keydown', (e) => {
+ if (e.target.closest('input, textarea, select, button, a, [contenteditable=true]')) return;
if (e.key === 'ArrowRight' || e.key === ' ') {
e.preventDefault();
nextSlide();
@@ -1411,48 +1318,46 @@
🚀 Next Module
function createPageDots() {
const container = document.getElementById('pageDots');
for (let i = 1; i <= totalSlides; i++) {
- const dot = document.createElement('div');
+ const dot = document.createElement('button');
+ dot.type = 'button';
+ dot.setAttribute('aria-label', `Go to slide ${i}`);
dot.className = 'page-dot' + (i === 1 ? ' active' : '');
dot.onclick = () => goToSlide(i);
container.appendChild(dot);
}
}
- function updataUI() {
- // Updata progress bar
+ function updateUI() {
+ // Update progress bar
document.getElementById('progressBar').style.width =
`${(currentSlide / totalSlides) * 100}%`;
- // Updata counter
+ // Update counter
document.getElementById('slideCounter').textContent =
`${currentSlide} / ${totalSlides}`;
- // Updata buttons
+ // Update buttons
document.getElementById('btnPrev').disabled = currentSlide === 1;
document.getElementById('btnNext').textContent =
currentSlide === totalSlides ? 'Finish ✓' : 'Continue →';
- // Updata dots
+ // Update dots
document.querySelectorAll('.page-dot').forEach((dot, i) => {
dot.classList.toggle('active', i + 1 === currentSlide);
});
}
function goToSlide(n) {
- if (n < 1 || n > totalSlides || n === currentSlide) return;
-
- const currentEl = document.querySelector(`.slide[data-slide="${currentSlide}"]`);
- const nextEl = document.querySelector(`.slide[data-slide="${n}"]`);
-
- currentEl.classList.remove('active');
- currentEl.classList.add('exit');
-
- setTimeout(() => {
- currentEl.classList.remove('exit');
- nextEl.classList.add('active');
- currentSlide = n;
- updataUI();
- }, 100);
+ if (!Number.isInteger(n) || n < 1 || n > totalSlides) return;
+ currentSlide = n;
+ document.querySelectorAll('.slide').forEach(slide => {
+ const active = Number(slide.dataset.slide) === n;
+ slide.classList.remove('exit');
+ slide.classList.toggle('active', active);
+ slide.inert = !active;
+ slide.setAttribute('aria-hidden', String(!active));
+ });
+ updateUI();
}
function nextSlide() {
@@ -1482,25 +1387,31 @@
🚀 Next Module
}, 1000);
}
- function copyCode(btn) {
- const container = btn.closest('.code-container');
- const code = container.querySelector('pre').textContent;
- navigator.clipboard.writeText(code);
-
- const originalText = btn.textContent;
- btn.textContent = '✓ Copied!';
- setTimeout(() => btn.textContent = originalText, 1500);
+ async function copyCode(btn) {
+ const pre = btn.closest('.code-container').querySelector('pre');
+ const original = btn.textContent;
+ try {
+ await navigator.clipboard.writeText(pre.textContent);
+ btn.textContent = 'Copied!';
+ } catch (_) {
+ const range = document.createRange();
+ range.selectNodeContents(pre);
+ const selection = window.getSelection();
+ selection.removeAllRanges();
+ selection.addRange(range);
+ btn.textContent = 'Selected: copy manually';
+ }
+ setTimeout(() => { btn.textContent = original; }, 2000);
}
- // Quiz functions
function selectOption(el, quizId) {
const container = document.getElementById(quizId);
- container.querySelectorAll('.quiz-option').forEach(opt => {
- opt.classList.remove('selected', 'correct', 'incorrect');
+ container.querySelectorAll('.quiz-option').forEach(option => {
+ option.classList.remove('selected', 'correct', 'incorrect');
+ option.setAttribute('aria-pressed', 'false');
});
el.classList.add('selected');
-
- // Hide feedback when selecting new option
+ el.setAttribute('aria-pressed', 'true');
document.getElementById(`${quizId}-feedback`).classList.remove('visible');
}
@@ -1545,7 +1456,7 @@
🚀 Next Module
hintEl.classList.add('visible');
quizHintCounts[quizId] = currentHint;
- // Updata hint button
+ // Update hint button
const btn = document.querySelector(`#${quizId} .btn-hint`);
if (currentHint >= 3) {
btn.textContent = '✓ All hints shown';
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/02_reading_python_code.html b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/02_reading_python_code.html
index 636198a..6036e4c 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/02_reading_python_code.html
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/02_reading_python_code.html
@@ -668,7 +668,11 @@
margin: 0 -1rem;
padding: 0 1rem;
}
-
+ 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;}
+
@@ -689,6 +693,7 @@
+
Interactive outputs are prewritten demonstrations. Run the canonical scripts in the VM or supported Linux environment using the lab map .
📖
Reading Python Code
From Syntax to Deep Understanding
@@ -696,7 +701,7 @@
Reading Python Code
⏱️ ~25 minutes
📅 Weeks 1-2
- 📁 01roWSL, 02roWSL
+ 📁 04_SEMINARS/S01, 04_SEMINARS/S02
@@ -747,7 +752,7 @@
🎯 What will we learn in this module?
🔍
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.
@@ -1368,7 +1373,7 @@
💻 Sandbox: Experiment with the Code
@@ -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.
@@ -1511,9 +1516,11 @@
Practical Application in the Lab
const quizHintCounts = {};
document.addEventListener('DOMContentLoaded', () => {
- updataUI();
+ updateUI();
createPageDots();
+ goToSlide(currentSlide);
document.addEventListener('keydown', (e) => {
+ if (e.target.closest('input, textarea, select, button, a, [contenteditable=true]')) return;
if (e.key === 'ArrowRight' || e.key === ' ') { e.preventDefault(); nextSlide(); }
else if (e.key === 'ArrowLeft') { prevSlide(); }
});
@@ -1522,14 +1529,16 @@
Practical Application in the Lab
function createPageDots() {
const container = document.getElementById('pageDots');
for (let i = 1; i <= totalSlides; i++) {
- const dot = document.createElement('div');
+ const dot = document.createElement('button');
+ dot.type = 'button';
+ dot.setAttribute('aria-label', `Go to slide ${i}`);
dot.className = 'page-dot' + (i === 1 ? ' active' : '');
dot.onclick = () => goToSlide(i);
container.appendChild(dot);
}
}
- function updataUI() {
+ function updateUI() {
document.getElementById('progressBar').style.width = `${(currentSlide / totalSlides) * 100}%`;
document.getElementById('slideCounter').textContent = `${currentSlide} / ${totalSlides}`;
document.getElementById('btnPrev').disabled = currentSlide === 1;
@@ -1540,17 +1549,16 @@
Practical Application in the Lab
}
function goToSlide(n) {
- if (n < 1 || n > totalSlides || n === currentSlide) return;
- const currentEl = document.querySelector(`.slide[data-slide="${currentSlide}"]`);
- const nextEl = document.querySelector(`.slide[data-slide="${n}"]`);
- currentEl.classList.remove('active');
- currentEl.classList.add('exit');
- setTimeout(() => {
- currentEl.classList.remove('exit');
- nextEl.classList.add('active');
- currentSlide = n;
- updataUI();
- }, 100);
+ if (!Number.isInteger(n) || n < 1 || n > totalSlides) return;
+ currentSlide = n;
+ document.querySelectorAll('.slide').forEach(slide => {
+ const active = Number(slide.dataset.slide) === n;
+ slide.classList.remove('exit');
+ slide.classList.toggle('active', active);
+ slide.inert = !active;
+ slide.setAttribute('aria-hidden', String(!active));
+ });
+ updateUI();
}
function nextSlide() { if (currentSlide < totalSlides) goToSlide(currentSlide + 1); }
@@ -1562,26 +1570,36 @@
Practical Application in the Lab
btn.disabled = true;
setTimeout(() => {
output.classList.add('visible');
- btn.textContent = '▶ Run';
+ btn.textContent = '▶ Simulate';
btn.disabled = false;
}, 800);
}
- function copyCode(btn) {
- const container = btn.closest('.code-container');
- const code = container.querySelector('pre').textContent;
- navigator.clipboard.writeText(code);
- const originalText = btn.textContent;
- btn.textContent = '✓ Copied!';
- setTimeout(() => btn.textContent = originalText, 1500);
+ async function copyCode(btn) {
+ const pre = btn.closest('.code-container').querySelector('pre');
+ const original = btn.textContent;
+ try {
+ await navigator.clipboard.writeText(pre.textContent);
+ btn.textContent = 'Copied!';
+ } catch (_) {
+ const range = document.createRange();
+ range.selectNodeContents(pre);
+ const selection = window.getSelection();
+ selection.removeAllRanges();
+ selection.addRange(range);
+ btn.textContent = 'Selected: copy manually';
+ }
+ setTimeout(() => { btn.textContent = original; }, 2000);
}
function selectOption(el, quizId) {
const container = document.getElementById(quizId);
- container.querySelectorAll('.quiz-option').forEach(opt => {
- opt.classList.remove('selected', 'correct', 'incorrect');
+ container.querySelectorAll('.quiz-option').forEach(option => {
+ option.classList.remove('selected', 'correct', 'incorrect');
+ option.setAttribute('aria-pressed', 'false');
});
el.classList.add('selected');
+ el.setAttribute('aria-pressed', 'true');
document.getElementById(`${quizId}-feedback`).classList.remove('visible');
}
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/03_data_types_networking.html b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/03_data_types_networking.html
index e6afe00..bdff57e 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/03_data_types_networking.html
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/03_data_types_networking.html
@@ -138,7 +138,11 @@
.python-logo { font-size: 4rem; margin-bottom: 1rem; }
.hex-display { font-family: var(--font-mono); background: var(--code-bg); padding: 0.5rem 1rem; border-radius: 8px; display: inline-block; margin: 0.5rem; }
.hex-byte { color: var(--accent-primary); margin: 0 2px; }
-
+ 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;}
+
@@ -152,6 +156,7 @@
+
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()
@@ -327,7 +332,7 @@
📦 Bytes Literal — Writing Directly
@@ -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
@@ -513,7 +518,7 @@
📚 Dict Comprehensions — Parsing Headers
@@ -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
@@ -588,7 +593,7 @@
🧪 Experiment: bytes in a Real Exercise
1
Open the TCP exercise
-
code 02roWSL/src/exercises/ex_2_01_tcp.py
+
code "00_APPENDIX/a)PYTHON_self_study_guide/examples/01_socket_tcp.py"
🎯 Purpose: This file implements a complete TCP server and client
@@ -642,22 +647,22 @@
Quiz 1: bytes vs str
-
+
A
str.bytes()
-
-
+
+
B
str.encode('utf-8')
-
-
+
+
C
bytes(str)
-
-
+
+
D
str.tobytes()
-
+
@@ -678,7 +683,7 @@
Quiz 1: bytes vs str
Option B: "text".encode('utf-8') returns b'text'
-
+
@@ -700,22 +705,22 @@ Quiz 2: List Comprehension
-
+
A
[2, 4, 6, 8]
-
-
+
+
B
[3, 4]
-
-
+
+
C
[6, 8]
-
-
+
+
D
[1, 2, 6, 8]
-
+
@@ -736,7 +741,7 @@
Quiz 2: List Comprehension
3 * 2 = 6, 4 * 2 = 8 → Result: [6, 8]
-
+
@@ -752,22 +757,22 @@
Quiz 3: Bytes Literal
-
+
A
12
-
-
+
+
B
160
-
-
+
+
C
192
-
-
+
+
D
255
-
+
@@ -788,7 +793,7 @@
Quiz 3: Bytes Literal
12 × 16 = 192. This is the first octet of the IP address 192.168.x.x!
-
+
@@ -802,7 +807,7 @@ 💻 Sandbox: Experiment
@@ -840,8 +845,8 @@
💻 Sandbox: Experiment
Reconstructed: 192.168.1.100
--- HTTP Request ---
-Text length: 46 characters
-Bytes length: 46 bytes
+Text length: 47 characters
+Bytes length: 47 bytes
Request bytes: b'GET /api/data HTTP/1.1\r\nHost: 192.168.1.100\r\n'...
@@ -864,14 +869,14 @@ 📂 Where to Find These Concepts in the Lab
-
📁 02roWSL
-
ex_2_01_tcp.py
+
📁 04_SEMINARS/S02
+
00_APPENDIX/a)PYTHON_self_study_guide/examples/01_socket_tcp.py
encode() when sending messages
decode() when receiving responses
TCP client-server pattern
-
ex_2_02_udp.py
+
04_SEMINARS/S02/S02_Part07_Example_UDP_Server.py
Same pattern for UDP
sendto() and recvfrom()
@@ -879,13 +884,13 @@ 📁 02roWSL
-
📁 03roWSL
-
ex_3_01_udp_broadcast.py
+
📁 04_SEMINARS/S03
+
04_SEMINARS/S03/4_udp-broadcast/S03_Part04A_Example_UDP_Broad_Sender.py
Bytes for UDP broadcast
SO_BROADCAST socket option
-
ex_3_03_tcp_tunnel.py
+
03_LECTURES/C03/assets/scenario-tcp-tunnel/tunnel.py
Forwarding bytes between connections
Without encode/decode (binary data!)
@@ -968,9 +973,11 @@ 🚀 Next Module
const quizHintCounts = {};
document.addEventListener('DOMContentLoaded', () => {
- updataUI();
+ updateUI();
createPageDots();
+ goToSlide(currentSlide);
document.addEventListener('keydown', (e) => {
+ if (e.target.closest('input, textarea, select, button, a, [contenteditable=true]')) return;
if (e.key === 'ArrowRight' || e.key === ' ') { e.preventDefault(); nextSlide(); }
else if (e.key === 'ArrowLeft') { prevSlide(); }
});
@@ -979,14 +986,16 @@ 🚀 Next Module
function createPageDots() {
const container = document.getElementById('pageDots');
for (let i = 1; i <= totalSlides; i++) {
- const dot = document.createElement('div');
+ const dot = document.createElement('button');
+ dot.type = 'button';
+ dot.setAttribute('aria-label', `Go to slide ${i}`);
dot.className = 'page-dot' + (i === 1 ? ' active' : '');
dot.onclick = () => goToSlide(i);
container.appendChild(dot);
}
}
- function updataUI() {
+ function updateUI() {
document.getElementById('progressBar').style.width = `${(currentSlide / totalSlides) * 100}%`;
document.getElementById('slideCounter').textContent = `${currentSlide} / ${totalSlides}`;
document.getElementById('btnPrev').disabled = currentSlide === 1;
@@ -995,11 +1004,16 @@ 🚀 Next Module
}
function goToSlide(n) {
- if (n < 1 || n > totalSlides || n === currentSlide) return;
- const currentEl = document.querySelector(`.slide[data-slide="${currentSlide}"]`);
- const nextEl = document.querySelector(`.slide[data-slide="${n}"]`);
- currentEl.classList.remove('active'); currentEl.classList.add('exit');
- setTimeout(() => { currentEl.classList.remove('exit'); nextEl.classList.add('active'); currentSlide = n; updataUI(); }, 100);
+ if (!Number.isInteger(n) || n < 1 || n > totalSlides) return;
+ currentSlide = n;
+ document.querySelectorAll('.slide').forEach(slide => {
+ const active = Number(slide.dataset.slide) === n;
+ slide.classList.remove('exit');
+ slide.classList.toggle('active', active);
+ slide.inert = !active;
+ slide.setAttribute('aria-hidden', String(!active));
+ });
+ updateUI();
}
function nextSlide() { if (currentSlide < totalSlides) goToSlide(currentSlide + 1); }
@@ -1008,18 +1022,34 @@ 🚀 Next Module
function simulateRun(btn, outputId) {
const output = document.getElementById(outputId);
btn.textContent = '⏳ Run...'; btn.disabled = true;
- setTimeout(() => { output.classList.add('visible'); btn.textContent = '▶ Run'; btn.disabled = false; }, 800);
+ setTimeout(() => { output.classList.add('visible'); btn.textContent = '▶ Simulate'; btn.disabled = false; }, 800);
}
- function copyCode(btn) {
- const code = btn.closest('.code-container').querySelector('pre').textContent;
- navigator.clipboard.writeText(code);
- const orig = btn.textContent; btn.textContent = '✓ Copied!'; setTimeout(() => btn.textContent = orig, 1500);
+ async function copyCode(btn) {
+ const pre = btn.closest('.code-container').querySelector('pre');
+ const original = btn.textContent;
+ try {
+ await navigator.clipboard.writeText(pre.textContent);
+ btn.textContent = 'Copied!';
+ } catch (_) {
+ const range = document.createRange();
+ range.selectNodeContents(pre);
+ const selection = window.getSelection();
+ selection.removeAllRanges();
+ selection.addRange(range);
+ btn.textContent = 'Selected: copy manually';
+ }
+ setTimeout(() => { btn.textContent = original; }, 2000);
}
function selectOption(el, quizId) {
- document.getElementById(quizId).querySelectorAll('.quiz-option').forEach(o => o.classList.remove('selected','correct','incorrect'));
+ const container = document.getElementById(quizId);
+ container.querySelectorAll('.quiz-option').forEach(option => {
+ option.classList.remove('selected', 'correct', 'incorrect');
+ option.setAttribute('aria-pressed', 'false');
+ });
el.classList.add('selected');
+ el.setAttribute('aria-pressed', 'true');
document.getElementById(`${quizId}-feedback`).classList.remove('visible');
}
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/04_socket_programming.html b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/04_socket_programming.html
index e3e3d37..b3f3049 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/04_socket_programming.html
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/04_socket_programming.html
@@ -133,7 +133,11 @@
.flow-step { background: var(--bg-tertiary); padding: 0.75rem 1.5rem; border-radius: 8px; font-family: var(--font-mono); font-size: 0.9rem; border: 1px solid var(--border-color); }
.flow-step.highlight { background: rgba(0, 212, 170, 0.2); border-color: var(--accent-primary); color: var(--accent-primary); }
.flow-arrow { color: var(--text-muted); }
-
+ 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;}
+
@@ -147,6 +151,7 @@
+
Interactive outputs are prewritten demonstrations. Run the canonical scripts in the VM or supported Linux environment using the lab map .
🔌
Socket Programming
TCP and UDP — The Foundation of Network Communication
@@ -344,7 +349,7 @@
💻 TCP Server — Complete Code
@@ -666,22 +671,22 @@
📝 Quiz: Check Your Understanding
-
+
A
socket.SOCK_DGRAM
-
-
+
+
B
socket.SOCK_STREAM
-
-
+
+
C
socket.SOCK_RAW
-
-
+
+
D
socket.SOCK_TCP
-
+
@@ -693,7 +698,7 @@
📝 Quiz: Check Your Understanding
Hint 2/3
SOCK_STREAM = TCP, SOCK_DGRAM = UDP. There is no SOCK_TCP.
Hint 3/3
Answer: SOCK_STREAM because TCP provides a "stream" of bytes.
-
+
@@ -712,22 +717,22 @@ 📝 Quiz: Check Your Understanding
-
+
A
socket → listen → bind → accept
-
-
+
+
B
socket → bind → listen → accept
-
-
+
+
C
socket → accept → bind → listen
-
-
+
+
D
socket → connect → listen → accept
-
+
@@ -739,7 +744,7 @@
📝 Quiz: Check Your Understanding
Hint 2/3
listen() marks the socket as passive. accept() comes after listen().
Hint 3/3
connect() is for the CLIENT, not the server. The server does bind → listen → accept.
-
+
@@ -753,22 +758,22 @@
📝 Quiz: Check Your Understanding
-
+
A
Creates a socket and connects it automatically
-
-
+
+
B
Creates a socket that cannot be closed
-
-
+
+
C
Creates a socket and guarantees it closes when leaving the block
-
-
+
+
D
Creates a persistent socket between sessions
-
+
@@ -780,7 +785,7 @@
📝 Quiz: Check Your Understanding
Hint 2/3
It is equivalent to try-finally where the finally block calls close().
Hint 3/3
Even if an exception occurs, with guarantees that socket.close() is called.
-
+
@@ -837,7 +842,7 @@ 🔧 Common Patterns in Exercises
🌐
Where can you find these patterns?
-
02roWSL/src/apps/ contains complete examples of servers and clients that you can study.
+
00_APPENDIX/a)PYTHON_self_study_guide/examples/ contains complete examples of servers and clients that you can study.
@@ -903,13 +908,13 @@ 📂 Files to Study in the Lab
-
📁 02roWSL — TCP/UDP Basics
-
ex_2_01_tcp.py
+
📁 04_SEMINARS/S02 — TCP/UDP Basics
+
00_APPENDIX/a)PYTHON_self_study_guide/examples/01_socket_tcp.py
Complete TCP server and client
Echo server pattern
-
ex_2_02_udp.py
+
04_SEMINARS/S02/S02_Part07_Example_UDP_Server.py
UDP server and client
sendto() and recvfrom()
@@ -917,13 +922,13 @@ 📁 02roWSL — TCP/UDP Basics
-
📁 03roWSL — Advanced
-
ex_3_01_udp_broadcast.py
+
📁 04_SEMINARS/S03 — Advanced
+
04_SEMINARS/S03/4_udp-broadcast/S03_Part04A_Example_UDP_Broad_Sender.py
UDP Broadcast
SO_BROADCAST option
-
ex_3_02_udp_multicast.py
+
04_SEMINARS/S03/5_udp-multicast/S03_Part05A_Example_UDP_Multicast_Sender.py
Multicast groups
IP_ADD_MEMBERSHIP
@@ -931,8 +936,8 @@ 📁 03roWSL — Advanced
-
📁 04roWSL — Protocols
-
binary_proto_server.py
+
📁 04_SEMINARS/S04 — Protocols
+
04_SEMINARS/S04/2_binary-proto_tcp/S04_Part02A_Example_Binary_Proto_TCP_Server.py
Custom binary protocol
Header + payload
@@ -940,11 +945,11 @@ 📁 04roWSL — Protocols
-
📁 src/apps/ — Complete Apps
+
📁 Canonical examples and exercises
- Fully working complete examples
- Reference code (do not modify)
- Patterns to follow
+ Read each seminar README for launch commands and dependencies
+ Modify the supplied template for the assigned task
+ Compare behaviour with the complete example
@@ -1006,7 +1011,9 @@ 🚀 Next Module
document.addEventListener('DOMContentLoaded', () => {
updateUI();
createPageDots();
+ goToSlide(currentSlide);
document.addEventListener('keydown', (e) => {
+ if (e.target.closest('input, textarea, select, button, a, [contenteditable=true]')) return;
if (e.key === 'ArrowRight' || e.key === ' ') {
e.preventDefault();
nextSlide();
@@ -1019,7 +1026,9 @@ 🚀 Next Module
function createPageDots() {
const container = document.getElementById('pageDots');
for (let i = 1; i <= totalSlides; i++) {
- const dot = document.createElement('div');
+ const dot = document.createElement('button');
+ dot.type = 'button';
+ dot.setAttribute('aria-label', `Go to slide ${i}`);
dot.className = 'page-dot' + (i === 1 ? ' active' : '');
dot.onclick = () => goToSlide(i);
container.appendChild(dot);
@@ -1037,17 +1046,16 @@ 🚀 Next Module
}
function goToSlide(n) {
- if (n < 1 || n > totalSlides || n === currentSlide) return;
- const currentEl = document.querySelector(`.slide[data-slide="${currentSlide}"]`);
- const nextEl = document.querySelector(`.slide[data-slide="${n}"]`);
- currentEl.classList.remove('active');
- currentEl.classList.add('exit');
- setTimeout(() => {
- currentEl.classList.remove('exit');
- nextEl.classList.add('active');
- currentSlide = n;
- updateUI();
- }, 100);
+ if (!Number.isInteger(n) || n < 1 || n > totalSlides) return;
+ currentSlide = n;
+ document.querySelectorAll('.slide').forEach(slide => {
+ const active = Number(slide.dataset.slide) === n;
+ slide.classList.remove('exit');
+ slide.classList.toggle('active', active);
+ slide.inert = !active;
+ slide.setAttribute('aria-hidden', String(!active));
+ });
+ updateUI();
}
function nextSlide() {
@@ -1069,19 +1077,31 @@ 🚀 Next Module
}, 800);
}
- function copyCode(btn) {
- const code = btn.closest('.code-container').querySelector('pre').textContent;
- navigator.clipboard.writeText(code);
- const orig = btn.textContent;
- btn.textContent = '✓ Copied!';
- setTimeout(() => btn.textContent = orig, 1500);
+ async function copyCode(btn) {
+ const pre = btn.closest('.code-container').querySelector('pre');
+ const original = btn.textContent;
+ try {
+ await navigator.clipboard.writeText(pre.textContent);
+ btn.textContent = 'Copied!';
+ } catch (_) {
+ const range = document.createRange();
+ range.selectNodeContents(pre);
+ const selection = window.getSelection();
+ selection.removeAllRanges();
+ selection.addRange(range);
+ btn.textContent = 'Selected: copy manually';
+ }
+ setTimeout(() => { btn.textContent = original; }, 2000);
}
function selectOption(el, quizId) {
- document.getElementById(quizId).querySelectorAll('.quiz-option').forEach(o => {
- o.classList.remove('selected', 'correct', 'incorrect');
+ const container = document.getElementById(quizId);
+ container.querySelectorAll('.quiz-option').forEach(option => {
+ option.classList.remove('selected', 'correct', 'incorrect');
+ option.setAttribute('aria-pressed', 'false');
});
el.classList.add('selected');
+ el.setAttribute('aria-pressed', 'true');
document.getElementById(`${quizId}-feedback`).classList.remove('visible');
}
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/05_code_organisation.html b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/05_code_organisation.html
index 4387f0a..ecc8f9a 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/05_code_organisation.html
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/05_code_organisation.html
@@ -119,7 +119,11 @@
.file-tree-item.highlight { color: var(--accent-primary); font-weight: 600; }
.indent-1 { padding-left: 1.5rem; }
.indent-2 { padding-left: 3rem; }
-
+ 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;}
+
@@ -132,6 +136,7 @@
+
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 Structure How exercises are organised in netROwsl
+
Project Structure How exercises are organised in COMPNET-EN
@@ -184,7 +189,8 @@ 📦 Functions in Python
# Simple function
def calculate_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
@@ -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.
+
Canonical lab map
+
-
🔑 The if __name__ == "__main__" Pattern
@@ -323,7 +308,7 @@
💡 Why is this useful?
📥 Using utils/ in Exercises
-
+
"""Exercise 4.01: Data Link Frame Analysis."""
@@ -367,24 +352,24 @@ 🧪 Experiment: Explore the Structure
1
-
Explore utils/
-
ls 04roWSL/src/utils/
-
🎯 What you will see: Helper files available for import
+
Explore examples/
+
ls "00_APPENDIX/a)PYTHON_self_study_guide/examples/"
+
🎯 What you will see: Standalone examples and their tests
2
Read a utility module
-
cat 04roWSL/src/utils/network.py
-
🎯 What you will see: Documented and tested functions
+
cat "00_APPENDIX/a)PYTHON_self_study_guide/examples/03_struct_parsing.py"
+
🎯 What you will see: The IPHeader dataclass and parse_ip_header function
3
Run the module directly
-
python3 04roWSL/src/utils/network.py
+
python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/03_struct_parsing.py"
🎯 What we learn: The __main__ block enables quick testing
@@ -402,10 +387,10 @@ 📝 Quiz
What does if __name__ == "__main__" do?
-
A Makes the file executable on Linux
-
B Executes code only when the file is run directly, not when imported
-
C Defines the mandatory main function
-
D Creates an entry point for debugging
+
A Makes the file executable on Linux
+
B Executes code only when the file is run directly, not when imported
+
C Defines the mandatory main function
+
D Creates an entry point for debugging
Check
@@ -414,7 +399,7 @@
📝 Quiz
Hint 1/3
__name__ is a special variable. When you run a file directly, its value is "__main__".
Hint 2/3
When you import a module, __name__ takes the module name instead of "__main__".
Hint 3/3
Answer B: it allows you to include test code that does not run when the module is imported.
-
+
@@ -458,7 +443,9 @@
🚀 Next Module
document.addEventListener('DOMContentLoaded', () => {
updateUI();
createPageDots();
+ goToSlide(currentSlide);
document.addEventListener('keydown', (e) => {
+ if (e.target.closest('input, textarea, select, button, a, [contenteditable=true]')) return;
if (e.key === 'ArrowRight' || e.key === ' ') {
e.preventDefault();
nextSlide();
@@ -471,7 +458,9 @@
🚀 Next Module
function createPageDots() {
const container = document.getElementById('pageDots');
for (let i = 1; i <= totalSlides; i++) {
- const dot = document.createElement('div');
+ const dot = document.createElement('button');
+ dot.type = 'button';
+ dot.setAttribute('aria-label', `Go to slide ${i}`);
dot.className = 'page-dot' + (i === 1 ? ' active' : '');
dot.onclick = () => goToSlide(i);
container.appendChild(dot);
@@ -489,17 +478,16 @@
🚀 Next Module
}
function goToSlide(n) {
- if (n < 1 || n > totalSlides || n === currentSlide) return;
- const current = document.querySelector(`.slide[data-slide="${currentSlide}"]`);
- const next = document.querySelector(`.slide[data-slide="${n}"]`);
- current.classList.remove('active');
- current.classList.add('exit');
- setTimeout(() => {
- current.classList.remove('exit');
- next.classList.add('active');
- currentSlide = n;
- updateUI();
- }, 100);
+ if (!Number.isInteger(n) || n < 1 || n > totalSlides) return;
+ currentSlide = n;
+ document.querySelectorAll('.slide').forEach(slide => {
+ const active = Number(slide.dataset.slide) === n;
+ slide.classList.remove('exit');
+ slide.classList.toggle('active', active);
+ slide.inert = !active;
+ slide.setAttribute('aria-hidden', String(!active));
+ });
+ updateUI();
}
function nextSlide() {
@@ -511,10 +499,13 @@
🚀 Next Module
}
function selectOption(el, quizId) {
- document.getElementById(quizId).querySelectorAll('.quiz-option').forEach(o => {
- o.classList.remove('selected', 'correct', 'incorrect');
+ const container = document.getElementById(quizId);
+ container.querySelectorAll('.quiz-option').forEach(option => {
+ option.classList.remove('selected', 'correct', 'incorrect');
+ option.setAttribute('aria-pressed', 'false');
});
el.classList.add('selected');
+ el.setAttribute('aria-pressed', 'true');
document.getElementById(`${quizId}-feedback`).classList.remove('visible');
}
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/06_cli_interfaces.html b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/06_cli_interfaces.html
index f971ae2..e59240d 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/06_cli_interfaces.html
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/06_cli_interfaces.html
@@ -113,7 +113,11 @@
.title-slide { display: flex; flex-direction: column; justify-content: center; align-items: center; text-align: center; }
.title-meta { display: flex; flex-wrap: wrap; gap: 1rem; justify-content: center; margin: 2rem 0; }
.python-logo { font-size: 4rem; margin-bottom: 1rem; }
-
+ 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;}
+
@@ -126,6 +130,7 @@
+
Interactive outputs are prewritten demonstrations. Run the canonical scripts in the VM or supported Linux environment using the lab map .
⌨️
CLI Interfaces with argparse
Command Line Arguments
@@ -188,7 +193,7 @@
💡 argparse provides automatically:
📝 Basic Usage
-
+
import argparse
@@ -231,7 +236,7 @@ 📝 Basic Usage
🔀 Subcommands (git style)
-
A pattern used in exercises for --mode server and --mode client:
+
An illustrative parser with positional server and client subcommands:
@@ -287,7 +292,7 @@
📖 Auto-Generated Help
💡 Tip
-
Run any exercise with --help to see all available options!
+
For argparse programs, use --help. Other scripts document positional arguments in their README or usage output.
@@ -341,7 +346,7 @@
🧪 Experiment: Test --help
1
Run --help on an exercise
-
python3 05roWSL/src/exercises/ex_5_01_cidr_flsm.py --help
+
python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/05_ping_latency.py" --help
🎯 What you will see: All arguments and their descriptions
@@ -349,7 +354,7 @@ Run --help on an exercise
2
Test with invalid arguments
-
python3 ex_5_01_cidr_flsm.py --port abc
+
python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/05_ping_latency.py" --count abc
🎯 What you will see: A clear error message from argparse
@@ -375,10 +380,10 @@
📝 Quiz
What does action="store_true" do?
-
A Stores the value as a string
-
B Sets True if the flag is present, False otherwise
-
C Automatically converts to boolean
-
D Requires an explicit True or False value
+
A Stores the value as a string
+
B Sets True if the flag is present, False otherwise
+
C Automatically converts to boolean
+
D Requires an explicit True or False value
Check
@@ -387,34 +392,18 @@
📝 Quiz
Hint 1/3
Think about -v for verbose. You do not write "-v True", just "-v".
Hint 2/3
Flag presence = True, absence = False (the default value).
Hint 3/3
Answer B: -v sets args.verbose = True
-
+
-
-
-
📂 Files with argparse in the Lab
-
-
-
📁 05roWSL
-
ex_5_01_cidr_flsm.py — Subnet calculation
-
--network 192.168.1.0/24 --hosts 50
-
ex_5_02_vlsm_ipv6.py — VLSM and IPv6
-
-
-
📁 All exercises
-
Most follow this pattern:
-
--mode server|client
-
--host IP --port PORT
-
-v for verbose
-
-
-
-
+
+
Real command interfaces Run from the repository root:
python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/05_ping_latency.py" --help
+python3 03_LECTURES/C05/assets/scenario-cidr-basic/cidr-calc.py 192.168.23.233/24
+python3 00_TOOLS/lab_runner/lab_runner.py --help 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.
+
-
✅ Summary
@@ -453,7 +442,9 @@
🚀 Next Module
document.addEventListener('DOMContentLoaded', () => {
updateUI();
createPageDots();
+ goToSlide(currentSlide);
document.addEventListener('keydown', (e) => {
+ if (e.target.closest('input, textarea, select, button, a, [contenteditable=true]')) return;
if (e.key === 'ArrowRight' || e.key === ' ') {
e.preventDefault();
nextSlide();
@@ -466,7 +457,9 @@
🚀 Next Module
function createPageDots() {
const container = document.getElementById('pageDots');
for (let i = 1; i <= totalSlides; i++) {
- const dot = document.createElement('div');
+ const dot = document.createElement('button');
+ dot.type = 'button';
+ dot.setAttribute('aria-label', `Go to slide ${i}`);
dot.className = 'page-dot' + (i === 1 ? ' active' : '');
dot.onclick = () => goToSlide(i);
container.appendChild(dot);
@@ -484,17 +477,16 @@
🚀 Next Module
}
function goToSlide(n) {
- if (n < 1 || n > totalSlides || n === currentSlide) return;
- const current = document.querySelector(`.slide[data-slide="${currentSlide}"]`);
- const next = document.querySelector(`.slide[data-slide="${n}"]`);
- current.classList.remove('active');
- current.classList.add('exit');
- setTimeout(() => {
- current.classList.remove('exit');
- next.classList.add('active');
- currentSlide = n;
- updateUI();
- }, 100);
+ if (!Number.isInteger(n) || n < 1 || n > totalSlides) return;
+ currentSlide = n;
+ document.querySelectorAll('.slide').forEach(slide => {
+ const active = Number(slide.dataset.slide) === n;
+ slide.classList.remove('exit');
+ slide.classList.toggle('active', active);
+ slide.inert = !active;
+ slide.setAttribute('aria-hidden', String(!active));
+ });
+ updateUI();
}
function nextSlide() {
@@ -510,15 +502,18 @@
🚀 Next Module
btn.textContent = '⏳...';
setTimeout(() => {
output.classList.add('visible');
- btn.textContent = '▶ Run';
+ btn.textContent = '▶ Simulate';
}, 500);
}
function selectOption(el, quizId) {
- document.getElementById(quizId).querySelectorAll('.quiz-option').forEach(o => {
- o.classList.remove('selected', 'correct', 'incorrect');
+ const container = document.getElementById(quizId);
+ container.querySelectorAll('.quiz-option').forEach(option => {
+ option.classList.remove('selected', 'correct', 'incorrect');
+ option.setAttribute('aria-pressed', 'false');
});
el.classList.add('selected');
+ el.setAttribute('aria-pressed', 'true');
document.getElementById(`${quizId}-feedback`).classList.remove('visible');
}
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/07_packet_analysis.html b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/07_packet_analysis.html
index 908320d..f1b84e9 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/07_packet_analysis.html
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/07_packet_analysis.html
@@ -7,7 +7,11 @@
+ 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;}
+
@@ -20,6 +24,7 @@
+
Interactive outputs are prewritten demonstrations. Run the canonical scripts in the VM or supported Linux environment using the lab map .
📦
Packet Analysis with struct
Parsing Protocol Headers
@@ -93,7 +98,7 @@
🔑 Byte Order (Endianness)
📖 Parsing an IP Header
-
+
import struct
import socket
@@ -139,7 +144,7 @@ 📖 Parsing an IP Header
✍️ Building a Packet
-
+
import struct
import socket
@@ -227,7 +232,7 @@ 📦 Parsing TCP Header
📏 struct Utilities
-
+
import struct
@@ -270,8 +275,8 @@ 📏 struct Utilities
📂 In Lab Exercises
-
📁 06roWSL — NAT
-
ex_6_01_nat_simple.py
+
📁 04_SEMINARS/S06 — NAT
+
03_LECTURES/C06/assets/scenario-nat-linux/nat-demo.sh
Parse IP src/dst
Modify addresses (NAT)
@@ -279,8 +284,8 @@ 📁 06roWSL — NAT
-
📁 07roWSL — Firewall
-
ex_7_01_packet_filter.py
+
📁 04_SEMINARS/S07 — Firewall
+
04_SEMINARS/S07/2_packet-filter/S07_Part02A_Script_Packet_Filter.py
-
A Little Endian (Intel)
-
B Network byte order (Big Endian)
-
C Native byte order
-
D Exclude padding
+
A Little Endian (Intel)
+
B Network byte order (Big Endian)
+
C Native byte order
+
D Exclude padding
Check
@@ -357,7 +362,7 @@
📝 Quiz
Hint 1/3
Network protocols use a standard for byte order. Which one is it?
Hint 2/3
Big Endian = MSB first. Intel uses Little Endian natively.
Hint 3/3
! = Network byte order = Big Endian. ALWAYS use this for network packets!
-
+
@@ -371,10 +376,10 @@
📝 Quiz
What does struct.unpack('!HH', data) return?
-
A A single integer of 4 bytes
-
B A tuple with 2 integers, each 2 bytes
-
C A list with 4 bytes
-
D A string of 4 characters
+
A A single integer of 4 bytes
+
B A tuple with 2 integers, each 2 bytes
+
C A list with 4 bytes
+
D A string of 4 characters
Check
@@ -383,7 +388,7 @@
📝 Quiz
Hint 1/3
H = unsigned short = 2 bytes. How many H are in the format?
Hint 2/3
unpack() always returns a tuple.
Hint 3/3
2 x H = 2 integers of 16 bits each, returned as tuple.
-
+
@@ -427,7 +432,9 @@
🚀 Next Module
document.addEventListener("DOMContentLoaded", () => {
updateUI();
createPageDots();
+ goToSlide(currentSlide);
document.addEventListener("keydown", (e) => {
+ if (e.target.closest('input, textarea, select, button, a, [contenteditable=true]')) return;
if (e.key === "ArrowRight" || e.key === " ") {
e.preventDefault();
nextSlide();
@@ -440,7 +447,9 @@
🚀 Next Module
function createPageDots() {
const container = document.getElementById("pageDots");
for (let i = 1; i <= totalSlides; i++) {
- const dot = document.createElement("div");
+ const dot = document.createElement("button");
+ dot.type = "button";
+ dot.setAttribute("aria-label", `Go to slide ${i}`);
dot.className = "page-dot" + (i === 1 ? " active" : "");
dot.onclick = () => goToSlide(i);
container.appendChild(dot);
@@ -461,17 +470,16 @@
🚀 Next Module
}
function goToSlide(n) {
- if (n < 1 || n > totalSlides || n === currentSlide) return;
- const cur = document.querySelector(`.slide[data-slide="${currentSlide}"]`);
- const nxt = document.querySelector(`.slide[data-slide="${n}"]`);
- cur.classList.remove("active");
- cur.classList.add("exit");
- setTimeout(() => {
- cur.classList.remove("exit");
- nxt.classList.add("active");
- currentSlide = n;
- updateUI();
- }, 100);
+ if (!Number.isInteger(n) || n < 1 || n > totalSlides) return;
+ currentSlide = n;
+ document.querySelectorAll('.slide').forEach(slide => {
+ const active = Number(slide.dataset.slide) === n;
+ slide.classList.remove('exit');
+ slide.classList.toggle('active', active);
+ slide.inert = !active;
+ slide.setAttribute('aria-hidden', String(!active));
+ });
+ updateUI();
}
function nextSlide() {
@@ -491,12 +499,15 @@
🚀 Next Module
}, 500);
}
- function selectOption(el, qid) {
- document.getElementById(qid)
- .querySelectorAll(".quiz-option")
- .forEach((o) => o.classList.remove("selected", "correct", "incorrect"));
- el.classList.add("selected");
- document.getElementById(`${qid}-feedback`).classList.remove("visible");
+ function selectOption(el, quizId) {
+ const container = document.getElementById(quizId);
+ container.querySelectorAll('.quiz-option').forEach(option => {
+ option.classList.remove('selected', 'correct', 'incorrect');
+ option.setAttribute('aria-pressed', 'false');
+ });
+ el.classList.add('selected');
+ el.setAttribute('aria-pressed', 'true');
+ document.getElementById(`${quizId}-feedback`).classList.remove('visible');
}
function checkAnswer(qid) {
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/08_concurrency.html b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/08_concurrency.html
index 84194ab..75126f0 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/08_concurrency.html
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/08_concurrency.html
@@ -7,7 +7,11 @@
+ 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;}
+
@@ -20,6 +24,7 @@
+
Interactive outputs are prewritten demonstrations. Run the canonical scripts in the VM or supported Linux environment using the lab map .
🔄
Concurrency with threading
Multi-Client Servers
@@ -78,7 +83,7 @@
✅ Concurrent Server
🧵 The threading Module
-
+
from threading import Thread
import time
@@ -326,23 +331,23 @@ Daemon Thread
📂 Files with Threading in Lab
-
📁 07-09roWSL
-
ex_7_02_concurrent_server.py
+
📁 S03 — TCP concurrency
+
04_SEMINARS/S03/S03_Part01_Example_TCP_Multi_client_Server.py
Multi-client TCP server
handle_client() pattern
-
ex_9_01_proxy_server.py
+
03_LECTURES/C03/assets/scenario-tcp-tunnel/tunnel.py
- Proxy that forwards connections
- Thread per client↔server connection
+ TCP tunnel forwarding bytes in both directions
+ Per-connection relay threads; consult its README
-
📁 13roWSL
-
ex_13_01_chat_server.py
+
📁 Project S01 — implementation task
+
02_PROJECTS/01_network_applications/S01_multi_client_tcp_chat_text_protocol_and_presence.md
- Multi-user chat server
+ Design and implement a multi-user chat server
Broadcast messages to all clients
Lock for client list
@@ -361,10 +366,10 @@
📝 Quiz
What does thread.join() do?
-
A Starts the thread
-
B Forcefully stops the thread
-
C Blocks until thread finishes
-
D Combines two threads
+
A Starts the thread
+
B Forcefully stops the thread
+
C Blocks until thread finishes
+
D Combines two threads
Check
@@ -373,7 +378,7 @@
📝 Quiz
Hint 1/3
join = "wait for it to join" (to finish)
Hint 2/3
After join(), you know for sure the thread has finished execution
Hint 3/3
join() blocks the current thread until the target thread finishes
-
+
@@ -387,10 +392,10 @@
📝 Quiz
Why do we use Lock?
-
A To stop a thread
-
B To prevent race conditions on shared data
-
C To speed up execution
-
D To create new threads
+
A To stop a thread
+
B To prevent race conditions on shared data
+
C To speed up execution
+
D To create new threads
Check
@@ -399,7 +404,7 @@
📝 Quiz
Hint 1/3
What happens if 2 threads modify the same variable simultaneously?
Hint 2/3
Lock = "padlock". Only one thread can "enter" at a time.
Hint 3/3
Lock serialises access to shared resources, preventing data corruption.
-
+
@@ -443,7 +448,9 @@
🚀 Next Module
document.addEventListener("DOMContentLoaded", () => {
updateUI();
createPageDots();
+ goToSlide(currentSlide);
document.addEventListener("keydown", (e) => {
+ if (e.target.closest('input, textarea, select, button, a, [contenteditable=true]')) return;
if (e.key === "ArrowRight" || e.key === " ") {
e.preventDefault();
nextSlide();
@@ -456,7 +463,9 @@
🚀 Next Module
function createPageDots() {
const container = document.getElementById("pageDots");
for (let i = 1; i <= totalSlides; i++) {
- const dot = document.createElement("div");
+ const dot = document.createElement("button");
+ dot.type = "button";
+ dot.setAttribute("aria-label", `Go to slide ${i}`);
dot.className = "page-dot" + (i === 1 ? " active" : "");
dot.onclick = () => goToSlide(i);
container.appendChild(dot);
@@ -477,17 +486,16 @@
🚀 Next Module
}
function goToSlide(n) {
- if (n < 1 || n > totalSlides || n === currentSlide) return;
- const cur = document.querySelector(`.slide[data-slide="${currentSlide}"]`);
- const nxt = document.querySelector(`.slide[data-slide="${n}"]`);
- cur.classList.remove("active");
- cur.classList.add("exit");
- setTimeout(() => {
- cur.classList.remove("exit");
- nxt.classList.add("active");
- currentSlide = n;
- updateUI();
- }, 100);
+ if (!Number.isInteger(n) || n < 1 || n > totalSlides) return;
+ currentSlide = n;
+ document.querySelectorAll('.slide').forEach(slide => {
+ const active = Number(slide.dataset.slide) === n;
+ slide.classList.remove('exit');
+ slide.classList.toggle('active', active);
+ slide.inert = !active;
+ slide.setAttribute('aria-hidden', String(!active));
+ });
+ updateUI();
}
function nextSlide() {
@@ -507,12 +515,15 @@
🚀 Next Module
}, 500);
}
- function selectOption(el, qid) {
- document.getElementById(qid)
- .querySelectorAll(".quiz-option")
- .forEach((o) => o.classList.remove("selected", "correct", "incorrect"));
- el.classList.add("selected");
- document.getElementById(`${qid}-feedback`).classList.remove("visible");
+ function selectOption(el, quizId) {
+ const container = document.getElementById(quizId);
+ container.querySelectorAll('.quiz-option').forEach(option => {
+ option.classList.remove('selected', 'correct', 'incorrect');
+ option.setAttribute('aria-pressed', 'false');
+ });
+ el.classList.add('selected');
+ el.setAttribute('aria-pressed', 'true');
+ document.getElementById(`${quizId}-feedback`).classList.remove('visible');
}
function checkAnswer(qid) {
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/09_http_protocols.html b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/09_http_protocols.html
index 0393fb2..c1d9e02 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/09_http_protocols.html
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/09_http_protocols.html
@@ -7,7 +7,11 @@
+ 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;}
+
@@ -20,6 +24,7 @@
+
Interactive outputs are prewritten demonstrations. Run the canonical scripts in the VM or supported Linux environment using the lab map .
🌐
HTTP and Application Protocols
From Request to Response
@@ -63,7 +68,7 @@
📥 Response
HTTP/1.1 200 OK
Content-Type: application/json
-Content-Length: 42
+Content-Length: 27
Date: Mon, 01 Jan 2024 12:00:00 GMT
{"users": ["alice", "bob"]}
@@ -110,7 +115,7 @@
Idempotent
🔌 Manual HTTP with Sockets
-
+
import socket
@@ -208,7 +213,7 @@ 📖 Parsing HTTP Response
📦 The requests Library — The Easy Way
In practice, you use the requests library which handles everything automatically:
-
+
import requests
@@ -342,8 +347,8 @@ 5xx — Server Error
📂 HTTP Files in Lab
-
📁 08roWSL
-
ex_8_01_server_http.py
+
📁 04_SEMINARS/S08
+
04_SEMINARS/S08/3_socket-http/S08_Part03B_Example_Socket_HTTP_Server.py
Basic HTTP server
Request parsing
@@ -351,13 +356,13 @@ 📁 08roWSL
-
📁 10-12roWSL
-
ex_10_01_email_client.py
+
📁 C11–C12 — other application protocols
+
03_LECTURES/C12/assets/scenario-local-mailbox/README.md
-
ex_11_01_dns_lookup.py
+
03_LECTURES/C11/assets/scenario-dns-ttl-caching/README.md
@@ -376,10 +381,10 @@
📝 Quiz
What separates headers from body in HTTP?
-
A \n\n
-
B \r\n\r\n (blank CRLF line)
-
C ---
-
D Content-Length header
+
A \n\n
+
B \r\n\r\n (blank CRLF line)
+
C ---
+
D Content-Length header
Check
@@ -388,7 +393,7 @@
📝 Quiz
Hint 1/3
HTTP uses CRLF (\r\n) as line ending.
Hint 2/3
A blank line means two consecutive CRLFs.
Hint 3/3
\r\n\r\n = end of headers, start of body.
-
+
@@ -402,10 +407,10 @@
📝 Quiz
Which HTTP method is idempotent?
-
A POST
-
B GET
-
C PATCH
-
D None
+
A POST
+
B GET
+
C PATCH
+
D None
Check
@@ -414,7 +419,7 @@
📝 Quiz
Hint 1/3
Idempotent = same operation multiple times produces same result.
Hint 2/3
GET only reads data; it does not modify anything.
Hint 3/3
GET, PUT and DELETE are idempotent. POST is not (it creates new resources).
-
+
@@ -458,7 +463,9 @@
🚀 Next Module
document.addEventListener('DOMContentLoaded', () => {
updateUI();
createPageDots();
+ goToSlide(currentSlide);
document.addEventListener('keydown', (e) => {
+ if (e.target.closest('input, textarea, select, button, a, [contenteditable=true]')) return;
if (e.key === 'ArrowRight' || e.key === ' ') {
e.preventDefault();
nextSlide();
@@ -471,7 +478,9 @@
🚀 Next Module
function createPageDots() {
const container = document.getElementById('pageDots');
for (let i = 1; i <= totalSlides; i++) {
- const dot = document.createElement('div');
+ const dot = document.createElement('button');
+ dot.type = 'button';
+ dot.setAttribute('aria-label', `Go to slide ${i}`);
dot.className = 'page-dot' + (i === 1 ? ' active' : '');
dot.onclick = () => goToSlide(i);
container.appendChild(dot);
@@ -492,17 +501,16 @@
🚀 Next Module
}
function goToSlide(n) {
- if (n < 1 || n > totalSlides || n === currentSlide) return;
- const cur = document.querySelector(`.slide[data-slide="${currentSlide}"]`);
- const nxt = document.querySelector(`.slide[data-slide="${n}"]`);
- cur.classList.remove('active');
- cur.classList.add('exit');
- setTimeout(() => {
- cur.classList.remove('exit');
- nxt.classList.add('active');
- currentSlide = n;
- updateUI();
- }, 100);
+ if (!Number.isInteger(n) || n < 1 || n > totalSlides) return;
+ currentSlide = n;
+ document.querySelectorAll('.slide').forEach(slide => {
+ const active = Number(slide.dataset.slide) === n;
+ slide.classList.remove('exit');
+ slide.classList.toggle('active', active);
+ slide.inert = !active;
+ slide.setAttribute('aria-hidden', String(!active));
+ });
+ updateUI();
}
function nextSlide() {
@@ -518,16 +526,19 @@
🚀 Next Module
btn.textContent = '⏳...';
setTimeout(() => {
output.classList.add('visible');
- btn.textContent = '▶ Run';
+ btn.textContent = '▶ Simulate';
}, 500);
}
- function selectOption(el, qid) {
- document.getElementById(qid)
- .querySelectorAll('.quiz-option')
- .forEach((o) => o.classList.remove('selected', 'correct', 'incorrect'));
+ function selectOption(el, quizId) {
+ const container = document.getElementById(quizId);
+ container.querySelectorAll('.quiz-option').forEach(option => {
+ option.classList.remove('selected', 'correct', 'incorrect');
+ option.setAttribute('aria-pressed', 'false');
+ });
el.classList.add('selected');
- document.getElementById(`${qid}-feedback`).classList.remove('visible');
+ el.setAttribute('aria-pressed', 'true');
+ document.getElementById(`${quizId}-feedback`).classList.remove('visible');
}
function checkAnswer(qid) {
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/10_debugging_best_practices.html b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/10_debugging_best_practices.html
index 4ce0596..9fdca63 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/10_debugging_best_practices.html
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/PRESENTATIONS_EN/10_debugging_best_practices.html
@@ -7,7 +7,11 @@
+ 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;}
+
@@ -20,6 +24,7 @@
+
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()!
-
+
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.
@@ -390,10 +396,10 @@
📝 Quiz
Which logging level is correct for "connection lost"?
-
A DEBUG
-
B INFO
-
C WARNING
-
D CRITICAL
+
A DEBUG
+
B INFO
+
C WARNING
+
D CRITICAL
Check
@@ -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?
-
A pdb
-
B tcpdump / Wireshark
-
C pytest
-
D black
+
A pdb
+
B tcpdump / Wireshark
+
C pytest
+
D black
Check
@@ -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!
@@ -499,7 +505,9 @@
Next Steps
document.addEventListener('DOMContentLoaded', () => {
updateUI();
createPageDots();
+ goToSlide(currentSlide);
document.addEventListener('keydown', (e) => {
+ if (e.target.closest('input, textarea, select, button, a, [contenteditable=true]')) return;
if (e.key === 'ArrowRight' || e.key === ' ') {
e.preventDefault();
nextSlide();
@@ -512,7 +520,9 @@
Next Steps
function createPageDots() {
const container = document.getElementById('pageDots');
for (let i = 1; i <= totalSlides; i++) {
- const dot = document.createElement('div');
+ const dot = document.createElement('button');
+ dot.type = 'button';
+ dot.setAttribute('aria-label', `Go to slide ${i}`);
dot.className = 'page-dot' + (i === 1 ? ' active' : '');
dot.onclick = () => goToSlide(i);
container.appendChild(dot);
@@ -533,17 +543,16 @@
Next Steps
}
function goToSlide(n) {
- if (n < 1 || n > totalSlides || n === currentSlide) return;
- const cur = document.querySelector(`.slide[data-slide="${currentSlide}"]`);
- const nxt = document.querySelector(`.slide[data-slide="${n}"]`);
- cur.classList.remove('active');
- cur.classList.add('exit');
- setTimeout(() => {
- cur.classList.remove('exit');
- nxt.classList.add('active');
- currentSlide = n;
- updateUI();
- }, 100);
+ if (!Number.isInteger(n) || n < 1 || n > totalSlides) return;
+ currentSlide = n;
+ document.querySelectorAll('.slide').forEach(slide => {
+ const active = Number(slide.dataset.slide) === n;
+ slide.classList.remove('exit');
+ slide.classList.toggle('active', active);
+ slide.inert = !active;
+ slide.setAttribute('aria-hidden', String(!active));
+ });
+ updateUI();
}
function nextSlide() {
@@ -559,16 +568,19 @@
Next Steps
btn.textContent = '⏳...';
setTimeout(() => {
output.classList.add('visible');
- btn.textContent = '▶ Run';
+ btn.textContent = '▶ Simulate';
}, 500);
}
- function selectOption(el, qid) {
- document.getElementById(qid)
- .querySelectorAll('.quiz-option')
- .forEach((o) => o.classList.remove('selected', 'correct', 'incorrect'));
+ function selectOption(el, quizId) {
+ const container = document.getElementById(quizId);
+ container.querySelectorAll('.quiz-option').forEach(option => {
+ option.classList.remove('selected', 'correct', 'incorrect');
+ option.setAttribute('aria-pressed', 'false');
+ });
el.classList.add('selected');
- document.getElementById(`${qid}-feedback`).classList.remove('visible');
+ el.setAttribute('aria-pressed', 'true');
+ document.getElementById(`${quizId}-feedback`).classList.remove('visible');
}
function checkAnswer(qid) {
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/PYTHON_NETWORKING_GUIDE.md b/00_APPENDIX/a)PYTHON_self_study_guide/PYTHON_NETWORKING_GUIDE.md
index 961e580..95f0786 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/PYTHON_NETWORKING_GUIDE.md
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/PYTHON_NETWORKING_GUIDE.md
@@ -2,9 +2,9 @@
## Complete Self-Study Guide
> **Supplementary material** for the Computer Networks course
-> **Repository:** [github.com/antonioclim/netROwsl](https://github.com/antonioclim/netROwsl)
+> **Repository:** [github.com/antonioclim/COMPNET-EN](https://github.com/antonioclim/COMPNET-EN)
> **Status:** Optional, not assessed
-> **Environment:** WSL2 + Ubuntu 22.04 + Docker + Portainer
+> **Environment:** MININET-SDN in VirtualBox (primary), or the separate WSL2 route; see [environment routes](../docs/environment_routes.md).
> **Version:** 3.0 — January 2025 (with CPA, PI and CREATE pedagogical enhancements)
---
@@ -24,8 +24,8 @@
- [Step 8: HTTP and Application Protocols](#step-8-http-and-application-protocols)
- [Step 9: Best Practices and Debugging](#step-9-best-practices-and-debugging)
4. [CREATE Exercises — Independent Design](#create-exercises--independent-design)
-5. [Aderstanding Check (Peer Instruction)](#understanding-check-peer-instruction)
-6. [Pair Programming Exercise](#pair-programming-exercise)
+5. [Understanding Check (Peer Instruction)](#understanding-check-peer-instruction)
+6. [Pair Programming Exercise](../docs/pair_programming_guide.md)
7. [Parsons Exercises (Code Rearrangement)](#parsons-exercises-code-rearrangement)
8. [Code Tracing Exercises](#code-tracing-exercises-execution-tracking)
9. [EVALUATE Exercise: Choose the Architecture](#evaluate-exercise-choose-the-architecture)
@@ -54,14 +54,14 @@ The Computer Networks lab exercises use **Python** as the primary implementation
┌─────────────────────────────────────────────────────────────────────────────┐
│ LAB WEEK │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
-│ │ Mandatory exercises (weekly kit from XXroWSL/) │ │
+│ │ Mandatory exercises (weekly kit from 04_SEMINARS/Sxx/) │ │
│ │ → Run the scripts, complete the TODOs │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────────────────────────────────────────────────────┐ │
│ │ OPTIONAL: Corresponding step from this guide │ │
-│ │ → Aderstand the Python concepts behind the code │ │
+│ │ → Understand the Python concepts behind the code │ │
│ │ → Explore additional deepening exercises │ │
│ └─────────────────────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
@@ -71,44 +71,36 @@ The Computer Networks lab exercises use **Python** as the primary implementation
## Repository Structure
-The `netROwsl` repository has a consistent structure for each week:
+The canonical course repository is **COMPNET-EN**. Earlier editions used a different weekly kit; the paths below now refer to this repository.
-```
-netROwsl/
-├── 01roWSL/ # Week 1
-│ ├── src/
-│ │ ├── exercises/ # ← MAIN EXERCISES
-│ │ │ ├── ex_1_01_latency_ping.py
-│ │ │ ├── ex_1_02_tcp_server_client.py
-│ │ │ └── ...
-│ │ ├── apps/ # Complete demo applications
-│ │ └── utils/ # Reusable helper functions
-│ ├── scripts/ # Orchestration scripts
-│ ├── docker/ # Docker configurations
-│ ├── docs/ # Documentation
-│ ├── tests/ # Automated tests
-│ └── README.md
-├── 02roWSL/ ... 14roWSL/
-```
+| Directory | Material |
+|---|---|
+| `03_LECTURES/C01/` through `C14/` | Lecture notes, diagrams and scenarios |
+| `04_SEMINARS/S01/` through `S14/` | Practical tasks, examples and templates |
+| `02_PROJECTS/` | Project specifications and evidence criteria |
+| `00_TOOLS/` | Shared setup, capture, rendering and validation tools |
+| `00_APPENDIX/a)PYTHON_self_study_guide/examples/` | Optional runnable Python examples |
+
+Read the [canonical lab map](CANONICAL_LAB_MAP.md) before copying commands. Commands below assume the **repository root** unless a preceding `cd` changes it. Generic module/package sketches are explicitly illustrative, not exact excerpts of seminar source.
### Week Correspondence Table
| Folder | Week | Networking Theme | Correlated Python Step |
|--------|------|------------------|------------------------|
-| `01roWSL` | W1-2 | Network fundamentals | Step 1: Reading code |
-| `02roWSL` | W2-3 | TCP/UDP socket programming | Step 2 + Step 3 |
-| `03roWSL` | W3 | Broadcast, Multicast, Tunnel | Step 3: Advanced sockets |
-| `04roWSL` | W4 | Physical/Data Link Layer | Step 4: Code organisation |
-| `05roWSL` | W5 | Network Layer, IP, Subnetting | Step 5: CLI argparse |
-| `06roWSL` | W6 | NAT/PAT, SDN | Step 6: Packet analysis |
-| `07roWSL` | W7 | Packet filtering, Firewall | Step 6: Analysis (continued) |
-| `08roWSL` | W8 | Transport Layer, HTTP | Step 7 + Step 8 |
-| `09roWSL` | W9 | Session/Presentation Layer | Step 8: HTTP |
-| `10roWSL` | W10 | Application Layer protocols | Step 8: Application protocols |
-| `11roWSL` | W11 | Load balancing, DNS | Step 8: REST, DNS |
-| `12roWSL` | W12 | Email, RPC | Step 8: Application protocols |
-| `13roWSL` | W13 | IoT, Security | Step 7 + Step 9 |
-| `14roWSL` | W14 | Recap, Projects | Step 9: Best practices |
+| `04_SEMINARS/S01` | W1-2 | Network fundamentals | Step 1: Reading code |
+| `04_SEMINARS/S02` | W2-3 | TCP/UDP socket programming | Step 2 + Step 3 |
+| `04_SEMINARS/S03` | W3 | Broadcast, Multicast, Tunnel | Step 3: Advanced sockets |
+| `04_SEMINARS/S04` | W4 | Text/binary protocols over TCP and UDP | Step 4: Code organisation |
+| `04_SEMINARS/S05` | W5 | Network Layer, IP, Subnetting | Step 5: CLI argparse |
+| `04_SEMINARS/S06` | W6 | NAT/PAT, SDN | Step 6: Packet analysis |
+| `04_SEMINARS/S07` | W7 | Packet filtering, Firewall | Step 6: Analysis (continued) |
+| `04_SEMINARS/S08` | W8 | Transport Layer, HTTP | Step 7 + Step 8 |
+| `04_SEMINARS/S09` | W9 | FTP and file transfer | Step 8: HTTP |
+| `04_SEMINARS/S10` | W10 | DNS, SSH and tunnels | Step 8: Application protocols |
+| `04_SEMINARS/S11` | W11 | Load balancing, DNS | Step 8: REST, DNS |
+| `04_SEMINARS/S12` | W12 | JSON-RPC, XML-RPC and gRPC | Step 8: Application protocols |
+| `04_SEMINARS/S13` | W13 | IoT, Security | Step 7 + Step 9 |
+| `04_SEMINARS/S14` | W14 | Recap, Projects | Step 9: Best practices |
---
@@ -116,7 +108,7 @@ netROwsl/
### Step 1: Reading Python Code
-**📅 Correlated with:** Weeks 1-2 (`01roWSL`, `02roWSL`)
+**📅 Correlated with:** Weeks 1-2 (`04_SEMINARS/S01`, `04_SEMINARS/S02`)
#### ═══════════════════════════════════════════════════════════════
#### 📋 CONTEXT_AND_ANALOGY
@@ -126,7 +118,7 @@ netROwsl/
Reading Python code is like reading a recipe before cooking:
-| Code Element | Recipe Equivaslow |
+| Code Element | Recipe Equivalent |
|--------------|-------------------|
| **Imports** (`import socket`) | Ingredient list — what you need before starting |
| **Functions** (`def server():`) | Recipe steps — instructions to follow in order |
@@ -147,8 +139,8 @@ Before modifying the lab scripts, you need to be able to read and understand the
#### Reference Files
Open and study the structure of these files:
-- `01roWSL/src/exercises/ex_1_01_latency_ping.py`
-- `01roWSL/src/exercises/ex_1_02_tcp_server_client.py`
+- `00_APPENDIX/a)PYTHON_self_study_guide/examples/05_ping_latency.py`
+- `00_APPENDIX/a)PYTHON_self_study_guide/examples/01_socket_tcp.py`
#### ═══════════════════════════════════════════════════════════════
#### 📖 KEY_CONCEPTS
@@ -185,7 +177,7 @@ class PingResult:
Compare with `struct` in C:
```c
-// C equivaslow
+// C equivalent
typedef struct {
int sequence;
float rtt_ms; // can be NULL?
@@ -239,8 +231,8 @@ Before running the command below, answer:
2. What happens if the host doesn't exist?
```bash
-cd /mnt/d/NETWORKING/netROwsl/01roWSL
-python3 src/exercises/ex_1_01_latency_ping.py --host 127.0.0.1 --count 5
+cd $HOME/COMPNET-EN
+python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/05_ping_latency.py" --host 127.0.0.1 --count 5
```
@@ -261,7 +253,7 @@ python3 src/exercises/ex_1_01_latency_ping.py --host 127.0.0.1 --count 5
### Step 2: Data Types for Networking
-**📅 Correlated with:** Weeks 2-3 (`02roWSL`, `03roWSL`)
+**📅 Correlated with:** Weeks 2-3 (`04_SEMINARS/S02`, `04_SEMINARS/S03`)
#### ═══════════════════════════════════════════════════════════════
#### 📋 CONTEXT_AND_ANALOGY
@@ -269,7 +261,7 @@ python3 src/exercises/ex_1_01_latency_ping.py --host 127.0.0.1 --count 5
#### 💡 Analogy: Bytes and Strings as Letters and Telegrams
-| Concept | Real Life Equivaslow |
+| Concept | Real Life Equivalent |
|---------|----------------------|
| **String** (`str`) | Letter in your language that you read directly |
| **Bytes** (`bytes`) | Telegram encoded in Morse — needs decoding |
@@ -284,8 +276,8 @@ Networks transport **bytes**, not text. Python makes an explicit distinction bet
#### Reference Files
-- `02roWSL/src/exercises/ex_2_01_tcp.py`
-- `02roWSL/src/exercises/ex_2_02_udp.py`
+- `00_APPENDIX/a)PYTHON_self_study_guide/examples/01_socket_tcp.py`
+- `04_SEMINARS/S02/S02_Part07_Example_UDP_Server.py`
#### ═══════════════════════════════════════════════════════════════
#### 📖 KEY_CONCEPTS
@@ -360,7 +352,7 @@ headers = {
#### 🔮 PREDICTION: Practical Exploration
-In `02roWSL/src/exercises/ex_2_01_tcp.py`:
+Illustrative byte conversion used with a connected TCP socket:
**Before looking at the code, predict:**
1. Where is the `encode()` conversion done?
@@ -378,7 +370,7 @@ In `02roWSL/src/exercises/ex_2_01_tcp.py`:
### Step 3: Socket Programming
-**📅 Correlated with:** Weeks 2-4 (`02roWSL`, `03roWSL`, `04roWSL`)
+**📅 Correlated with:** Weeks 2-4 (`04_SEMINARS/S02`, `04_SEMINARS/S03`, `04_SEMINARS/S04`)
#### ═══════════════════════════════════════════════════════════════
#### 📋 CONTEXT_AND_ANALOGY
@@ -386,7 +378,7 @@ In `02roWSL/src/exercises/ex_2_01_tcp.py`:
#### 💡 Analogy: Socket as a Landline Telephone
-| Socket Operation | Telephone Equivaslow |
+| Socket Operation | Telephone Equivalent |
|------------------|---------------------|
| `socket()` | You buy a new telephone |
| `bind()` | You get assigned a phone number (port) |
@@ -406,9 +398,9 @@ Sockets are the foundation of network communication. The exercises implement TCP
#### Reference Files
-- `02roWSL/src/exercises/ex_2_01_tcp.py` — TCP Server/Client
-- `02roWSL/src/exercises/ex_2_02_udp.py` — UDP Server/Client
-- `03roWSL/src/exercises/ex_3_01_udp_broadcast.py` — UDP Broadcast
+- `00_APPENDIX/a)PYTHON_self_study_guide/examples/01_socket_tcp.py` — TCP Server/Client
+- `04_SEMINARS/S02/S02_Part07_Example_UDP_Server.py` — UDP Server/Client
+- `04_SEMINARS/S03/4_udp-broadcast/S03_Part04A_Example_UDP_Broad_Sender.py` — UDP Broadcast
#### ═══════════════════════════════════════════════════════════════
#### 📖 KEY_CONCEPTS
@@ -445,7 +437,7 @@ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
**Question:** Why do we need `SO_REUSEADDR`?
-**Explanation:** When a server stops, the operating system keeps the port "reserved" for ~60 seconds (TIME_WAIT). Without `SO_REUSEADDR`, you cannot restart the server immediately — you get "Address already in use".
+**Explanation:** A recently closed TCP connection can remain in `TIME_WAIT`; this is connection state, not a universal reservation of every use of that port. Rebinding depends on the OS, addresses and reuse settings. On Linux, set `SO_REUSEADDR` before `bind()` when restart-friendly reuse is intended, including on the previous socket. It does not take over an address still used by an active conflicting listener. First check for an existing server with `ss -ltnp`.
**Practical consequence:** Always add this line before `bind()`:
```python
@@ -503,8 +495,8 @@ def run_server(host: str, port: int):
#### 🔮 PREDICTION: Practical Exploration
```bash
-cd /mnt/d/NETWORKING/netROwsl/02roWSL
-python3 src/exercises/ex_2_01_tcp.py --mode server --port 9090
+cd $HOME/COMPNET-EN
+python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/01_socket_tcp.py" server 9090
```
**Predict:**
@@ -525,7 +517,7 @@ python3 src/exercises/ex_2_01_tcp.py --mode server --port 9090
### Step 4: Code Organisation
-**📅 Correlated with:** Week 4 (`04roWSL`)
+**📅 Correlated with:** Week 4 (`04_SEMINARS/S04`)
#### ═══════════════════════════════════════════════════════════════
#### 📋 CONTEXT_AND_ANALOGY
@@ -533,7 +525,7 @@ python3 src/exercises/ex_2_01_tcp.py --mode server --port 9090
#### 💡 Analogy: Python Modules as Drawers in a Cabinet
-| Code Element | Cabinet Equivaslow |
+| Code Element | Cabinet Equivalent |
|--------------|-------------------|
| **`.py` file** | A drawer with a specific purpose |
| **`import`** | You open the drawer and take what you need |
@@ -546,7 +538,7 @@ python3 src/exercises/ex_2_01_tcp.py --mode server --port 9090
#### Why It Matters
-The kits have a consistent structure: `src/`, `scripts/`, `utils/`. Aderstanding the organisation helps you navigate and reuse code.
+The following `src/`, `scripts/`, `utils/` layout is an illustrative project design. COMPNET-EN units use their own README, scenario directories and explicitly named scripts; consult the canonical map for runnable files.
#### ═══════════════════════════════════════════════════════════════
#### 📖 KEY_CONCEPTS
@@ -555,7 +547,7 @@ The kits have a consistent structure: `src/`, `scripts/`, `utils/`. Aderstanding
#### Modular Structure
```
-04roWSL/src/
+example_project/src/
├── __init__.py # Makes src/ a Python "package"
├── exercises/
│ ├── __init__.py
@@ -596,7 +588,7 @@ from src.utils import calculate_crc
### Step 5: CLI Interfaces
-**📅 Correlated with:** Week 5 (`05roWSL`)
+**📅 Correlated with:** Week 5 (`04_SEMINARS/S05`)
#### ═══════════════════════════════════════════════════════════════
#### 📋 CONTEXT_AND_ANALOGY
@@ -604,7 +596,7 @@ from src.utils import calculate_crc
#### 💡 Analogy: argparse as a Restaurant Menu
-| CLI Element | Restaurant Equivaslow |
+| CLI Element | Restaurant Equivalent |
|-------------|----------------------|
| **Command** (`python script.py`) | You enter the restaurant |
| **Positional arguments** (`192.168.1.0`) | Main order (mandatory) |
@@ -636,7 +628,7 @@ args = parser.parse_args()
print(f"Dividing {args.network} into {args.subnets} subnets")
if args.verbose:
- print("Detailed mode activeated")
+ print("Detailed mode activated")
```
Usage:
@@ -648,7 +640,7 @@ python calculator.py 192.168.1.0/24 --subnets 8 -v
**Before running:**
```bash
-python3 ex_5_01_cidr_flsm.py --help
+python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/05_ping_latency.py" --help
```
**Predict:** What sections will the output have?
@@ -667,7 +659,7 @@ python3 ex_5_01_cidr_flsm.py --help
### Step 6: Packet Analysis
-**📅 Correlated with:** Weeks 6-7 (`06roWSL`, `07roWSL`)
+**📅 Correlated with:** Weeks 6-7 (`04_SEMINARS/S06`, `04_SEMINARS/S07`)
#### ═══════════════════════════════════════════════════════════════
#### 📋 CONTEXT_AND_ANALOGY
@@ -747,7 +739,7 @@ header = struct.pack('!HH', 8080, 443)
#### 💡 Analogy: Threading as Chefs in a Kitchen
-| Concurrency Element | Kitchen Equivaslow |
+| Concurrency Element | Kitchen Equivalent |
|--------------------|-------------------|
| **Thread** | An individual chef |
| **ThreadPool** | Team of chefs |
@@ -815,7 +807,7 @@ def scan_ports(host: str, ports: list[int], workers: int = 100) -> list[int]:
#### 💡 Analogy: HTTP as a Bank Conversation
-| HTTP Element | Bank Equivaslow |
+| HTTP Element | Bank Equivalent |
|--------------|-----------------|
| **Request** | You fill in a request form |
| **GET** | "I want to see my balance" (read only) |
@@ -859,7 +851,7 @@ def http_get(host: str, path: str, port: int = 80) -> str:
### Step 9: Best Practices and Debugging
-**📅 Correlated with:** Week 14 (`14roWSL`)
+**📅 Correlated with:** Week 14 (`04_SEMINARS/S14`)
#### ═══════════════════════════════════════════════════════════════
#### 📋 CONTEXT_AND_ANALOGY
@@ -867,13 +859,13 @@ def http_get(host: str, path: str, port: int = 80) -> str:
#### 💡 Analogy: Debugging as Detective Work
-| Debug Technique | Detective Equivaslow |
+| Debug Technique | Detective Equivalent |
|-----------------|---------------------|
| **print()** | You leave notes in key places |
| **logging** | CCTV camera recording everything |
| **breakpoint()** | You stop time and examine the scene |
| **Stack trace** | Timeline of events |
-| **Ait tests** | You verify each suspect's alibi |
+| **Unit tests** | You verify each suspect's alibi |
#### ═══════════════════════════════════════════════════════════════
#### 📖 KEY_CONCEPTS
@@ -929,7 +921,7 @@ Design and implement a simple binary protocol for a messaging system.
| Version | 1 byte | Protocol version (0x01) |
| Message type | 1 byte | 0x01=text, 0x02=image, 0x03=status |
| Length | 2 bytes | Payload length (big-endian) |
-| Timestamp | 4 bytes | Aix timestamp (seconds) |
+| Timestamp | 4 bytes | Unix timestamp (seconds) |
| Payload | variable | Message content |
#### Protocol Diagram
@@ -1116,7 +1108,7 @@ Functional `load_balancer.py` file with:
---
-## Aderstanding Check (Peer Instruction)
+## Understanding Check (Peer Instruction)
### 🗳️ PI #1: Bytes vs Strings
@@ -1279,7 +1271,7 @@ sock.close()
`sock.close()` never executes because of the exception.
**Why not A:** Exception occurs before close()
-**Why not C:** Python has no garbage collection for sockets
+**Why not C:** Garbage collection may close a socket, but its timing is not portable or deterministic. Use `with` or explicit `close()` for resource ownership.
**Why not D:** OS closes it eventually, but not immediately
**Solution:** Use `with socket.socket(...) as sock:`
@@ -1335,11 +1327,11 @@ data = sock.recv(10)
print(data)
```
-**Question:** What does the client display?
+**Question:** On a connected blocking TCP socket, assuming non-empty data arrives and no error occurs, which statement is guaranteed by recv(10)?
**Options:**
- A) `b'HELLO WORLD FROM SERVER!'`
-- B) `b'HELLO WORL'`
+- B) A non-empty prefix of the stream containing at most 10 bytes
- C) Error — buffer too small
- D) Nothing — recv() waits for 24 bytes
@@ -1350,9 +1342,9 @@ print(data)
`recv(10)` returns **at most** 10 bytes, not exactly 10 and not the entire message.
-**Why not A:** recv() doesn't wait for the whole message
+**Why not A:** The supplied buffer size limits this call to 10 bytes, so the whole longer literal cannot be returned.
**Why not C:** Buffer is only the upper limit, not requirement
-**Why not D:** recv() returns what's available, doesn't wait for more
+**Why not D:** recv(10) does not wait for a 24-byte application message. EOF or an exception are separate outcomes excluded by the question assumptions.
**Implication:** For longer messages, you need to call recv() in a loop or use a protocol with length prefix.
@@ -1977,17 +1969,17 @@ LEGEND: 8080 = HOST port (Windows sees this)
| File | What to explore | Python concept |
|------|-----------------|----------------|
-| `ex_1_01_latency_ping.py` | `@dataclass`, `subprocess.run()` | Dataclasses, subprocesses |
-| `ex_1_02_tcp_server_client.py` | `socket`, `threading` | Basic sockets |
-| `ex_1_03_csv_parsing.py` | `csv` module, comprehensions | Data processing |
+| `00_APPENDIX/a)PYTHON_self_study_guide/examples/05_ping_latency.py` | `@dataclass`, `subprocess.run()` | Dataclasses, subprocesses |
+| `00_APPENDIX/a)PYTHON_self_study_guide/examples/01_socket_tcp.py` | `socket`, `threading` | Basic sockets |
+| Python standard-library `csv` module (optional exercise design) | `csv.reader`, comprehensions | Data processing |
### Weeks 2-3: Sockets
| File | What to explore | Python concept |
|------|-----------------|----------------|
-| `ex_2_01_tcp.py` | `SOCK_STREAM`, `accept()` | TCP sockets |
-| `ex_2_02_udp.py` | `SOCK_DGRAM`, `sendto()` | UDP sockets |
-| `ex_3_01_udp_broadcast.py` | `SO_BROADCAST` | Socket options |
+| `00_APPENDIX/a)PYTHON_self_study_guide/examples/01_socket_tcp.py` | `SOCK_STREAM`, `accept()` | TCP sockets |
+| `04_SEMINARS/S02/S02_Part07_Example_UDP_Server.py` | `SOCK_DGRAM`, `sendto()` | UDP sockets |
+| `04_SEMINARS/S03/4_udp-broadcast/S03_Part04A_Example_UDP_Broad_Sender.py` | `SO_BROADCAST` | Socket options |
### Weeks 4-14: Advanced
@@ -2114,13 +2106,13 @@ docker ps -a | grep portainer
If stopped: `docker start portainer`. If doesn't exist, recreate it.
**Q: How do I reset the Portainer password if I forgot it?**
-A: Delete the data volume and recreate:
+A: Preserve the data volume and use the [official password helper](https://docs.portainer.io/advanced/reset-admin). First confirm the container name and `/data` mount with `docker inspect portainer`. If they are `portainer` and `portainer_data`, use:
```bash
docker stop portainer
-docker rm portainer
-docker volume rm portainer_data
-# Then recreate the container
+docker run --rm -v portainer_data:/data portainer/helper-reset-password
+docker start portainer
```
+Use the account and new password printed by the helper. This recovers the initial administrator account; another administrator can reset other users. See [environment routes](../docs/environment_routes.md).
**Q: Why does my socket "block" at recv()?**
A: `recv()` is blocking by default — it waits for data. Solutions:
@@ -2131,16 +2123,14 @@ sock.setblocking(False) # non-blocking (with select/poll)
```
**Q: Can I run GUI applications from WSL?**
-A: Yes, WSL2 on Windows 11 supports WSLg natively. On Windows 10 you need an X server (VcXsrv). But for this course, Wireshark runs natively on Windows, not in WSL.
+A: Current Store WSL supports WSLg on supported Windows 10 and Windows 11 installations. Check the installed WSL version; an external X server is only a fallback. The course also supports capturing inside Linux and opening the saved capture in Windows Wireshark.
**Q: Why do I get "Address already in use" when restarting the server?**
-A: The port is still in TIME_WAIT. Solutions:
-1. Wait ~60 seconds
-2. Add before bind():
+A: Check for an active listener first with `ss -ltnp`; another process may still own the address. A closed connection in `TIME_WAIT` can also affect rebinding, depending on the OS and socket options. For the Linux examples, set the intended reuse option before `bind()`:
```python
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
```
-3. Use a different port temporarily
+Apply this to the earlier socket as well when testing Linux restart behaviour. It does not displace an active listener. Stop only your own old server, or select a different free port. Any wait for `TIME_WAIT` expiry is platform-dependent, not a guaranteed 60-second remedy.
**Q: How do I see which ports are occupied?**
A:
@@ -2218,5 +2208,5 @@ Before considering this guide complete, check your progress:
---
*Material created as optional support for the Computer Networks course.*
-*Repository: [github.com/antonioclim/netROwsl](https://github.com/antonioclim/netROwsl)*
+*Repository: [github.com/antonioclim/COMPNET-EN](https://github.com/antonioclim/COMPNET-EN)*
*Version: 3.1 — January 2025 (with Parsons Problems, Code Tracing and self-assessment Checklist)*
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/comparisons/MISCONCEPTIONS_BY_BACKGROUND.md b/00_APPENDIX/a)PYTHON_self_study_guide/comparisons/MISCONCEPTIONS_BY_BACKGROUND.md
index c069a7f..df79ddc 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/comparisons/MISCONCEPTIONS_BY_BACKGROUND.md
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/comparisons/MISCONCEPTIONS_BY_BACKGROUND.md
@@ -63,7 +63,7 @@ packed = struct.pack('!H', 8080) # '!' = network order
```
```python
# Python: == is already strict (no coercion)
-if x == 5: # Works like ===
+if x == 5: # Value equality; numeric types can compare equal
# For identity (same object):
if x is None: # Use 'is', not ==
@@ -219,7 +219,7 @@ server.bind(('0.0.0.0', 8080)) # All interfaces
|-------|--------------|
| `TypeError: a bytes-like object required` | Forgot `.encode()` |
| `SyntaxError` on `{` | Using braces instead of `:` |
-| `NameError: 'const' not defined` | Using JS/Kotlin keywords |
+| `SyntaxError: invalid syntax not defined` | Using JS/Kotlin keywords |
| `AttributeError: no attribute` | Using dot notation on dict |
| `IndentationError` | Mixed tabs/spaces |
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/comparisons/README.md b/00_APPENDIX/a)PYTHON_self_study_guide/comparisons/README.md
index 61a3dc4..15a0c82 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/comparisons/README.md
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/comparisons/README.md
@@ -31,7 +31,7 @@ cd "00_APPENDIX/a)PYTHON_self_study_guide"
# read the Rosetta Stone first, then the misconceptions for your background
-# run the quiz subset tailored to your background
+# include common questions plus questions explicitly tagged for this background
make quiz-c
make quiz-js
make quiz-java
@@ -89,4 +89,4 @@ https://github.com/antonioclim/COMPNET-EN/tree/main/00_APPENDIX/a)PYTHON_self_st
| Item | Value |
|---|---|
| Scope | Optional student aid within the Python bridge pack |
-| Quiz filters | Implemented in `../formative/run_quiz.py` and configured in `../formative/quiz.yaml` |
+| Quiz filters | Common questions are included for every background; a small set has explicit C, JavaScript, Java or Kotlin tags. The filter is not a separate complete examination for each language. |
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/comparisons/ROSETTA_STONE.md b/00_APPENDIX/a)PYTHON_self_study_guide/comparisons/ROSETTA_STONE.md
index a4396ac..55fe3ac 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/comparisons/ROSETTA_STONE.md
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/comparisons/ROSETTA_STONE.md
@@ -2,7 +2,7 @@
## Side-by-Side Comparison with C, JavaScript, Java and Kotlin
> **Purpose:** If you know one of these languages, you already know Python's networking logic.
-> **Format:** Same algorithm, five implementations.
+> **Format:** Echo each received byte until EOF. C, Java, Kotlin and Python below serve clients sequentially; the Node event loop can serve several clients. These are core fragments: supply imports, a main function where required and error handling appropriate to the full application.
> **Version:** 4.1 — January 2026
---
@@ -35,15 +35,27 @@
```c
int server_fd = socket(AF_INET, SOCK_STREAM, 0);
setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
-struct sockaddr_in addr = {AF_INET, htons(8080), INADDR_ANY};
+struct sockaddr_in addr = {0};
+addr.sin_family = AF_INET;
+addr.sin_port = htons(8080);
+addr.sin_addr.s_addr = htonl(INADDR_ANY);
bind(server_fd, (struct sockaddr*)&addr, sizeof(addr));
listen(server_fd, 5);
while (1) {
int client_fd = accept(server_fd, NULL, NULL);
char buffer[1024];
- int n = recv(client_fd, buffer, 1024, 0);
- send(client_fd, buffer, n, 0); // Echo back
+ if (client_fd < 0) continue;
+ ssize_t n;
+ while ((n = recv(client_fd, buffer, sizeof buffer, 0)) > 0) {
+ ssize_t sent = 0;
+ while (sent < n) {
+ ssize_t part = send(client_fd, buffer + sent, (size_t)(n - sent), 0);
+ if (part <= 0) goto close_client;
+ sent += part;
+ }
+ }
+close_client:
close(client_fd);
}
```
@@ -52,6 +64,7 @@ while (1) {
```javascript
const net = require('net');
const server = net.createServer((socket) => {
+ socket.on('error', (error) => { console.error(error.message); socket.destroy(); });
socket.on('data', (data) => {
socket.write(data); // Echo back
});
@@ -65,8 +78,10 @@ try (ServerSocket serverSocket = new ServerSocket(8080)) {
while (true) {
try (Socket client = serverSocket.accept()) {
byte[] buffer = new byte[1024];
- int n = client.getInputStream().read(buffer);
- client.getOutputStream().write(buffer, 0, n); // Echo
+ int n;
+ while ((n = client.getInputStream().read(buffer)) != -1) {
+ client.getOutputStream().write(buffer, 0, n);
+ }
}
}
}
@@ -78,8 +93,11 @@ ServerSocket(8080).use { server ->
while (true) {
server.accept().use { client ->
val buffer = ByteArray(1024)
- val n = client.getInputStream().read(buffer)
- client.getOutputStream().write(buffer, 0, n) // Echo
+ while (true) {
+ val n = client.getInputStream().read(buffer)
+ if (n == -1) break
+ client.getOutputStream().write(buffer, 0, n)
+ }
}
}
}
@@ -97,18 +115,21 @@ with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
while True:
client, addr = server.accept()
with client:
- data = client.recv(1024)
- client.sendall(data) # Echo back
+ while True:
+ data = client.recv(1024)
+ if not data:
+ break
+ client.sendall(data) # Echo this chunk; TCP has no message boundary
```
### Key Observations
| Aspect | C | JS | Java | Kotlin | Python |
|--------|---|----|----|--------|--------|
-| Lines of code | ~15 | ~8 | ~12 | ~10 | ~10 |
+| Execution model | Blocking | Event-driven | Blocking | Blocking | Blocking |
| Manual memory | ✅ Yes | ❌ No | ❌ No | ❌ No | ❌ No |
| Resource cleanup | Manual close() | Callbacks | try-with-resources | .use {} | `with` statement |
-| Byte order | `htons()` | Automatic | Automatic | Automatic | Automatic |
+| Port in socket API | `htons()` in sockaddr | Host-order integer | Host-order integer | Host-order integer | Host-order integer |
---
@@ -133,8 +154,8 @@ const ip = view.getUint32(2, false);
### Java
```java
ByteBuffer buf = ByteBuffer.wrap(data).order(ByteOrder.BIG_ENDIAN);
-short port = buf.getShort();
-int ip = buf.getInt();
+int port = Short.toUnsignedInt(buf.getShort());
+long ip = Integer.toUnsignedLong(buf.getInt());
```
### Python ✨
@@ -169,11 +190,23 @@ if (connect(sock, &addr, sizeof(addr)) < 0) {
### JavaScript
```javascript
-try {
- await socket.connect(host, port);
-} catch (error) {
- console.error('Connection failed:', error.message);
+const net = require('net');
+function connectTo(host, port) {
+ return new Promise((resolve, reject) => {
+ const socket = net.createConnection({host, port});
+ socket.once('error', reject);
+ socket.once('connect', () => resolve(socket));
+ });
}
+(async () => {
+ try {
+ const socket = await connectTo('127.0.0.1', 8080);
+ // Perform the application exchange here; connect() itself is not a Promise.
+ socket.end();
+ } catch (error) {
+ console.error('Connection failed:', error.message);
+ }
+})();
```
### Java
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/docs/SELF_CHECK_CHECKPOINTS.md b/00_APPENDIX/a)PYTHON_self_study_guide/docs/SELF_CHECK_CHECKPOINTS.md
index e07817d..43f641f 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/docs/SELF_CHECK_CHECKPOINTS.md
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/docs/SELF_CHECK_CHECKPOINTS.md
@@ -1,6 +1,9 @@
# 🔍 Self-Check Checkpoints
## Quick Knowledge Verification for Each Learning Step
+The code-tracing examples are self-contained teaching scenarios. For files and wire protocols used in the actual COMPNET-EN seminars, use the unit README and the canonical Python lab map; a toy JSON or text example does not redefine the S04 protocol.
+
+
> **How to use:** After completing each Step in PYTHON_NETWORKING_GUIDE.md, answer these questions without looking at the materials. If you struggle with more than one question per section, review that Step before continuing.
---
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/docs/TROUBLESHOOTING.md b/00_APPENDIX/a)PYTHON_self_study_guide/docs/TROUBLESHOOTING.md
index dacfeb2..a54299c 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/docs/TROUBLESHOOTING.md
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/docs/TROUBLESHOOTING.md
@@ -18,7 +18,7 @@
| `ModuleNotFoundError: yaml` | PyYAML not installed | `pip install pyyaml` |
| `SyntaxError` on `{` | Using braces instead of colon | Use `:` and indentation |
| `IndentationError` | Mixed tabs and spaces | Use spaces only (4 per level) |
-| `NameError: 'const'` | Using JS/Kotlin keywords | Just assign: `PORT = 8080` |
+| `SyntaxError: invalid syntax` | Using JS/Kotlin keywords | Just assign: `PORT = 8080` |
| `AttributeError` on dict | Using dot notation | Use brackets: `d["key"]` |
| `UnicodeDecodeError` | Wrong encoding | Specify encoding or use `errors='replace'` |
@@ -66,21 +66,18 @@ ConnectionRefusedError: [Errno 111] Connection refused
**Cause:** The server is not running or is listening on a different port/address.
**Fix:**
-```python
-# 1. Start the server FIRST in one terminal:
-python server.py
+Run these commands from the repository root in Linux/WSL, using two terminals:
-# 2. Then run the client in another terminal:
-python client.py
+```bash
+# Terminal 1: start the canonical example server and leave it running.
+python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/01_socket_tcp.py" server 9090
-# 3. Verify server is listening:
-# Linux/WSL:
-netstat -tlnp | grep 8080
-# or
-ss -tlnp | grep 8080
+# Terminal 2: confirm the listener, then run the client.
+ss -tlnp 'sport = :9090'
+python3 "00_APPENDIX/a)PYTHON_self_study_guide/examples/01_socket_tcp.py" client 127.0.0.1 9090 "Hello"
```
-**Verify:** `netstat` shows the server listening on the expected port.
+**Verify:** `ss` shows the example listening on TCP port 9090 and the client prints its response. Stop the server with Ctrl+C when finished.
**Common mistakes:**
- Server bound to `127.0.0.1` but client connecting to `0.0.0.0`
@@ -248,13 +245,13 @@ expand -t 4 script.py > script_fixed.py
---
-### 8. NameError: name 'const' is not defined
+### 8. SyntaxError: invalid syntax
**When it appears:** Using JavaScript or Kotlin keywords in Python
**Error example:**
```
-NameError: name 'const' is not defined
+SyntaxError: invalid syntax
```
**Cause:** Python does not have `const`, `let`, `var`, `val` keywords.
@@ -272,7 +269,7 @@ counter = 0 # All variables are reassignable
host = "localhost"
```
-**Verify:** No NameError on execution.
+**Verify:** No SyntaxError when using PORT = 8080.
---
@@ -481,9 +478,11 @@ value, = struct.unpack(fmt, data[:expected_size])
Cannot connect to the Docker daemon at unix:///var/run/docker.sock
```
-**Cause:** Docker Desktop is not running or WSL integration is disabled.
+**Cause:** The selected Docker daemon is stopped or inaccessible. Use `docker context show` and `docker info`; follow the route actually installed.
**Fix:**
+For Docker Desktop only:
+
1. Start Docker Desktop on Windows
2. Wait for it to fully start (whale icon stable in system tray)
3. Check WSL integration: Docker Desktop → Settings → Resources → WSL Integration → Enable for your distro
@@ -533,3 +532,5 @@ If your issue is not listed here:
*Troubleshooting Guide — Python for Networking*
*Computer Networks Course — ASE Bucharest, CSIE*
*Version 5.0 — January 2026*
+
+For the primary VM and native WSL Engine routes, follow [environment routes](../../docs/environment_routes.md); Docker Desktop settings do not manage those daemons.
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/examples/02_bytes_vs_str.py b/00_APPENDIX/a)PYTHON_self_study_guide/examples/02_bytes_vs_str.py
index d58867b..175cfbb 100755
--- a/00_APPENDIX/a)PYTHON_self_study_guide/examples/02_bytes_vs_str.py
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/examples/02_bytes_vs_str.py
@@ -31,7 +31,8 @@
import tempfile
from typing import Any, Union
-__all__ = ['safe_decode', 'hex_dump', 'demonstrate_encoding', 'demonstrate_decoding']
+__all__ = ['safe_decode', 'hex_dump', 'ensure_bytes', 'ensure_str',
+ 'demonstrate_conversion', 'demonstrate_encoding_errors', 'binary_file_example']
# ═══════════════════════════════════════════════════════════════════════════════
# LOGGING_CONFIGURATION
@@ -258,7 +259,8 @@ def binary_file_example() -> None:
test_data: bytes = b'\x45\x00\x00\x28' # IPv4, IHL=5, length=40
# HACK: Use a temporary file to avoid polluting the system
- temp_path: str = os.path.join(tempfile.gettempdir(), 'test_packet.bin')
+ temp_dir = tempfile.TemporaryDirectory(prefix='compnet-bytes-')
+ temp_path: str = os.path.join(temp_dir.name, 'test_packet.bin')
try:
# ─────────────────────────────────────────────────────────────
@@ -298,9 +300,8 @@ def binary_file_example() -> None:
finally:
# NOTE: Cleanup — delete the temporary file
- if os.path.exists(temp_path):
- os.remove(temp_path)
- print(f"\n🧹 Cleanup: temporary file deleted")
+ temp_dir.cleanup()
+ print("\n🧹 Cleanup: this demonstration's temporary directory deleted")
# ═══════════════════════════════════════════════════════════════════════════════
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/examples/03_struct_parsing.py b/00_APPENDIX/a)PYTHON_self_study_guide/examples/03_struct_parsing.py
index 3f91d2c..abb7940 100755
--- a/00_APPENDIX/a)PYTHON_self_study_guide/examples/03_struct_parsing.py
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/examples/03_struct_parsing.py
@@ -35,7 +35,7 @@
from typing import Optional
from dataclasses import dataclass
-__all__ = ['IPHeader', 'TCPHeader', 'parse_ip_header', 'parse_tcp_header']
+__all__ = ['IPHeader', 'parse_ip_header', 'get_protocol_name', 'display_header']
# ═══════════════════════════════════════════════════════════════════════════════
# LOGGING_CONFIGURATION
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/examples/04_error_handling.py b/00_APPENDIX/a)PYTHON_self_study_guide/examples/04_error_handling.py
index eb7025f..6adeb31 100755
--- a/00_APPENDIX/a)PYTHON_self_study_guide/examples/04_error_handling.py
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/examples/04_error_handling.py
@@ -114,7 +114,10 @@ def connect_with_retry(
sock.connect((host, port))
logger.info(f"Connected successfully to {host}:{port}")
- return sock
+ # Transfer ownership to the caller before the finally block.
+ connected = sock
+ sock = None
+ return connected
except socket.timeout:
logger.warning(f"Attempt {attempt}: Connection timed out after {timeout}s")
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/examples/05_ping_latency.py b/00_APPENDIX/a)PYTHON_self_study_guide/examples/05_ping_latency.py
new file mode 100644
index 0000000..d0276ee
--- /dev/null
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/examples/05_ping_latency.py
@@ -0,0 +1,82 @@
+#!/usr/bin/env python3
+"""Read Linux ping results using a dataclass; run inside the VM or WSL Linux.
+
+Each observation runs one iputils ping with a bounded wait. The standard ping
+program performs ICMP; Python orchestrates it and parses its textual output.
+A result marked succeeded still needs an RTT match to contribute to statistics.
+"""
+from __future__ import annotations
+
+import argparse
+from dataclasses import dataclass
+import ipaddress
+import math
+import os
+import re
+import shutil
+import statistics
+import subprocess
+from typing import Optional
+
+
+@dataclass
+class PingResult:
+ sequence: int
+ rtt_ms: Optional[float]
+ succeeded: bool
+ message: str = ''
+
+
+def parse_ping_rtt(output: str) -> Optional[float]:
+ """Return iputils' millisecond RTT (an upper bound for a time< sample)."""
+ match = re.search(r'\btime[=<]\s*(\d+(?:\.\d+)?)\s*ms\b', output)
+ return float(match.group(1)) if match else None
+
+
+def run_ping(host: str, count: int = 3, timeout: float = 1.0) -> list[PingResult]:
+ try:
+ ipaddress.ip_address(host)
+ except ValueError:
+ if not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9._-]*', host):
+ raise ValueError('Use an IP address or hostname without shell syntax')
+ if not 1 <= count <= 100 or not 0 < timeout <= 60:
+ raise ValueError('count must be 1–100 and timeout must be greater than 0 and at most 60 seconds')
+ executable = shutil.which('ping')
+ if executable is None:
+ raise RuntimeError('Linux ping is missing; install the iputils-ping package in your lab environment')
+ results = []
+ for sequence in range(1, count + 1):
+ try:
+ process = subprocess.run(
+ [executable, '-n', '-c', '1', '-W', str(math.ceil(timeout)), host],
+ capture_output=True, text=True, timeout=timeout + 3,
+ env={**os.environ, 'LC_ALL': 'C'}, check=False)
+ rtt = parse_ping_rtt(process.stdout)
+ results.append(PingResult(sequence, rtt, process.returncode == 0,
+ process.stderr.strip() or ('RTT parser found no sample' if rtt is None else '')))
+ except subprocess.TimeoutExpired:
+ results.append(PingResult(sequence, None, False, 'ping process timed out'))
+ return results
+
+
+def main() -> int:
+ parser = argparse.ArgumentParser(description=__doc__)
+ parser.add_argument('--host', default='127.0.0.1')
+ parser.add_argument('--count', type=int, default=3)
+ parser.add_argument('--timeout', type=float, default=1.0)
+ args = parser.parse_args()
+ try:
+ results = run_ping(args.host, args.count, args.timeout)
+ except (ValueError, RuntimeError) as exc:
+ parser.error(str(exc))
+ for result in results:
+ print(result)
+ samples = [r.rtt_ms for r in results if r.succeeded and r.rtt_ms is not None]
+ print(f'Replies: {sum(r.succeeded for r in results)}/{len(results)}')
+ if samples:
+ print(f'RTT ms: min={min(samples):.3f}, mean={statistics.mean(samples):.3f}, max={max(samples):.3f}')
+ return 0 if len(samples) == len(results) else 1
+
+
+if __name__ == '__main__':
+ raise SystemExit(main())
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/examples/README.md b/00_APPENDIX/a)PYTHON_self_study_guide/examples/README.md
index 9e8362a..04c09dc 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/examples/README.md
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/examples/README.md
@@ -90,7 +90,7 @@ git sparse-checkout set "00_APPENDIX/a)PYTHON_self_study_guide/examples"
If you plan to run tests, also include the Python dependencies:
```bash
-git sparse-checkout add 00_APPENDIX/requirements.txt
+# requirements.txt in the ancestor 00_APPENDIX directory is included by cone mode.
```
Method B — Direct download (no Git required)
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/examples/tests/test_smoke.py b/00_APPENDIX/a)PYTHON_self_study_guide/examples/tests/test_smoke.py
index 112c900..032769e 100755
--- a/00_APPENDIX/a)PYTHON_self_study_guide/examples/tests/test_smoke.py
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/examples/tests/test_smoke.py
@@ -20,6 +20,7 @@
import subprocess
import sys
import os
+import importlib.util
from pathlib import Path
# NOTE: Auto-detect the examples/ directory
@@ -38,34 +39,38 @@
# ═══════════════════════════════════════════════════════════════════════════════
# TEST_IMPORTS
# ═══════════════════════════════════════════════════════════════════════════════
+def load_example(filename):
+ path = EXAMPLES_DIR / filename
+ assert path.is_file(), f"Required example is missing: {path}"
+ name = 'compnet_smoke_' + path.stem
+ spec = importlib.util.spec_from_file_location(name, path)
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[name] = module
+ spec.loader.exec_module(module)
+ for exported in getattr(module, '__all__', []):
+ assert hasattr(module, exported), f"{filename}: missing export {exported}"
+ return module
+
+
def test_socket_tcp_imports() -> None:
- """Verify that 01_socket_tcp.py imports without errors."""
- result = subprocess.run(
- [sys.executable, "-c", "import socket; import logging; import sys"],
- capture_output=True,
- timeout=10
- )
- assert result.returncode == 0, f"Import failed: {result.stderr.decode()}"
+ module = load_example('01_socket_tcp.py')
+ assert callable(module.server) and callable(module.client)
def test_bytes_vs_str_imports() -> None:
- """Verify that 02_bytes_vs_str.py imports without errors."""
- result = subprocess.run(
- [sys.executable, "-c", "from typing import Optional; import logging"],
- capture_output=True,
- timeout=10
- )
- assert result.returncode == 0, f"Import failed: {result.stderr.decode()}"
+ module = load_example('02_bytes_vs_str.py')
+ assert module.ensure_bytes('hello') == b'hello'
+ assert module.safe_decode(b'hello') == 'hello'
def test_struct_parsing_imports() -> None:
- """Verify that 03_struct_parsing.py imports without errors."""
- result = subprocess.run(
- [sys.executable, "-c", "import struct; from dataclasses import dataclass"],
- capture_output=True,
- timeout=10
- )
- assert result.returncode == 0, f"Import failed: {result.stderr.decode()}"
+ module = load_example('03_struct_parsing.py')
+ assert module.get_protocol_name(6) == 'TCP'
+
+
+def test_error_handling_imports() -> None:
+ module = load_example('04_error_handling.py')
+ assert callable(module.connect_with_retry) and callable(module.recv_exactly)
# ═══════════════════════════════════════════════════════════════════════════════
@@ -74,9 +79,7 @@ def test_struct_parsing_imports() -> None:
def test_bytes_demo_runs() -> None:
"""Run the bytes demonstration without errors."""
script_path = EXAMPLES_DIR / "02_bytes_vs_str.py"
- if not script_path.exists():
- print(f"SKIP: {script_path} does not exist")
- return
+ assert script_path.is_file(), f"Required example is missing: {script_path}"
result = subprocess.run(
[sys.executable, str(script_path)],
@@ -94,9 +97,7 @@ def test_bytes_demo_runs() -> None:
def test_struct_parsing_runs() -> None:
"""Run the struct demonstration without errors."""
script_path = EXAMPLES_DIR / "03_struct_parsing.py"
- if not script_path.exists():
- print(f"SKIP: {script_path} does not exist")
- return
+ assert script_path.is_file(), f"Required example is missing: {script_path}"
result = subprocess.run(
[sys.executable, str(script_path)],
@@ -158,6 +159,7 @@ def run_all_tests() -> bool:
test_socket_tcp_imports,
test_bytes_vs_str_imports,
test_struct_parsing_imports,
+ test_error_handling_imports,
test_bytes_encoding,
test_struct_pack_unpack,
test_socket_creation,
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/formative/README.md b/00_APPENDIX/a)PYTHON_self_study_guide/formative/README.md
index 38dd668..f4361fd 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/formative/README.md
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/formative/README.md
@@ -39,7 +39,7 @@ python3 run_quiz.py --review
# Parsons problems
python3 parsons_runner.py --list
-python3 parsons_runner.py --file parsons/parsons_socket.yaml
+python3 parsons_runner.py --file parsons_socket.yaml
```
The quiz runner saves results to `results/` by default. Use `--no-save` to disable this.
@@ -84,7 +84,7 @@ git sparse-checkout set "00_APPENDIX/a)PYTHON_self_study_guide/formative"
To run the quiz, also include the dependency list:
```bash
-git sparse-checkout add 00_APPENDIX/requirements.txt
+# requirements.txt in the ancestor 00_APPENDIX directory is included by cone mode.
```
Method B — Direct download (no Git required)
@@ -99,3 +99,7 @@ https://github.com/antonioclim/COMPNET-EN/tree/main/00_APPENDIX/a)PYTHON_self_st
|---|---|
| YAML source of truth | `quiz.yaml` and `parsons/*.yaml` |
| Output location | `results/` (local JSON result files) |
+
+## Scoring and filtering contract
+
+Background filters include shared foundation questions (`all`) and explicitly tagged language-comparison questions. They are a small adaptation, not a complete separate curriculum per language. The configured difficulty weights (1, 1.5 and 2) contribute to earned/planned points; skipped items earn zero. Results distinguish attempted, skipped and unattempted questions. A session ended early has no pass/readiness verdict; a completed session uses the bank's 70% threshold. Passing a formative quiz is not a substitute for running the practical tasks.
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/formative/parsons/parsons_bytes.yaml b/00_APPENDIX/a)PYTHON_self_study_guide/formative/parsons/parsons_bytes.yaml
index dc0477f..734adfc 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/formative/parsons/parsons_bytes.yaml
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/formative/parsons/parsons_bytes.yaml
@@ -1,6 +1,6 @@
# Parsons Problems: Bytes and Encoding
# Version: 5.0 — January 2026
-# Usage: python formative/parsons_runner.py --file parsons/parsons_bytes.yaml
+# Usage: python formative/parsons_runner.py --file parsons_bytes.yaml
metadata:
topic: "Bytes, Strings and Binary Protocol Parsing"
@@ -138,7 +138,7 @@ problems:
- {id: 6, code: "print(f'Decoded: {text}')", indent: 0}
distractors:
- - {id: D1, code: "text = str(data, 'utf-8')", indent: 1, hint: "This works but does not handle errors gracefully"}
+ - {id: D1, code: "text = str(data)", indent: 1, hint: "This returns the bytes representation, not decoded text; str(data, encoding) would be valid"}
- {id: D2, code: "except EncodingError:", indent: 0, hint: "The exception is UnicodeDecodeError, not EncodingError"}
correct_order: [1, 2, 3, 4, 5, 6]
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/formative/parsons/parsons_socket.yaml b/00_APPENDIX/a)PYTHON_self_study_guide/formative/parsons/parsons_socket.yaml
index 99a270b..1f20b0c 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/formative/parsons/parsons_socket.yaml
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/formative/parsons/parsons_socket.yaml
@@ -1,6 +1,6 @@
# Parsons Problems: Socket Programming
# Version: 5.0 — January 2026
-# Usage: python formative/parsons_runner.py --file parsons/parsons_socket.yaml
+# Usage: python formative/parsons_runner.py --file parsons_socket.yaml
metadata:
topic: "TCP/UDP Socket Programming"
@@ -150,7 +150,7 @@ problems:
distractors:
- {id: D1, code: "sock.timeout = 5.0", indent: 0, hint: "Use settimeout() method, not attribute assignment"}
- - {id: D2, code: "except TimeoutError:", indent: 0, hint: "Socket timeouts raise socket.timeout, not TimeoutError"}
+ - {id: D2, code: "except ConnectionRefusedError:", indent: 0, hint: "A refused connection is a different failure from a timeout; in Python 3.10+, socket.timeout and TimeoutError are aliases"}
correct_order: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/formative/parsons_runner.py b/00_APPENDIX/a)PYTHON_self_study_guide/formative/parsons_runner.py
index fb1c8c4..580bdb6 100755
--- a/00_APPENDIX/a)PYTHON_self_study_guide/formative/parsons_runner.py
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/formative/parsons_runner.py
@@ -318,9 +318,12 @@ def run_problems(
if i < len(problems):
input(f"\n{c.DIM}Press Enter for next problem...{c.RESET}")
- except KeyboardInterrupt:
+ except (KeyboardInterrupt, EOFError):
print(f"\n\n{c.YELLOW}Interrupted.{c.RESET}")
-
+
+ results['attempted'] = len(results['answers']) - results['skipped']
+ results['unattempted'] = results['total'] - len(results['answers'])
+ results['session_status'] = 'complete' if results['unattempted'] == 0 else 'incomplete'
return results
@@ -328,17 +331,21 @@ def display_results(results: Dict[str, Any]) -> None:
"""Display final results summary."""
c = Colours
- answered = results['total'] - results['skipped']
- if answered > 0:
- percentage = (results['correct'] / answered) * 100
- else:
- percentage = 0
+ answered = results['attempted']
+ planned = results['total']
+ percentage = (results['correct'] / planned) * 100 if planned else 0
print(f"\n{c.BOLD}{c.HEADER}{'═' * 70}{c.RESET}")
print(f"{c.BOLD}{c.HEADER} 📊 Results{c.RESET}")
print(f"{c.BOLD}{c.HEADER}{'═' * 70}{c.RESET}\n")
- if percentage >= 80:
+ if results['session_status'] != 'complete':
+ emoji = '⏸'
+ message = 'Incomplete session: this is feedback on attempted items, not a readiness verdict.'
+ elif answered == 0:
+ emoji = '⏸'
+ message = 'No answers attempted; no achievement verdict is available.'
+ elif percentage >= 80:
emoji = '🌟'
message = "Excellent! You understand the code structure well."
elif percentage >= 60:
@@ -348,8 +355,9 @@ def display_results(results: Dict[str, Any]) -> None:
emoji = '📚'
message = "Keep practising. Review the correct solutions carefully."
- print(f" {emoji} Score: {c.BOLD}{results['correct']}/{answered} ({percentage:.0f}%){c.RESET}")
- print(f" {c.DIM}Skipped: {results['skipped']}{c.RESET}")
+ print(f" {emoji} Score over planned items: {c.BOLD}{results['correct']}/{planned} ({percentage:.0f}%){c.RESET}")
+ print(f" {c.DIM}Attempted: {answered}; skipped items earn no credit.{c.RESET}")
+ print(f" {c.DIM}Skipped: {results['skipped']}; unattempted: {results['unattempted']}; planned: {results['total']}{c.RESET}")
print(f"\n {message}\n")
@@ -384,6 +392,8 @@ def main() -> None:
help='List available problem files')
args = parser.parse_args()
+ if args.limit is not None and args.limit <= 0:
+ parser.error('--limit must be a positive integer')
# Setup
if args.no_colour or not sys.stdout.isatty():
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/formative/quiz.yaml b/00_APPENDIX/a)PYTHON_self_study_guide/formative/quiz.yaml
index 52a83d0..c3cdf43 100644
--- a/00_APPENDIX/a)PYTHON_self_study_guide/formative/quiz.yaml
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/formative/quiz.yaml
@@ -8,11 +8,12 @@ metadata:
course: "Computer Networks"
estimated_time: "25-35 minutes"
passing_score: 70
- total_questions: 30
+ total_questions: 31
questions:
# --- Basic Syntax ---
- id: syn_01
+ target_background: [all]
section: basic_syntax
type: multiple_choice
difficulty: basic
@@ -27,6 +28,7 @@ questions:
explanation: "Python uses dynamic typing — no type declaration needed. Just assign: port = 8080"
- id: syn_02
+ target_background: [all]
section: basic_syntax
type: multiple_choice
difficulty: basic
@@ -41,6 +43,7 @@ questions:
explanation: "Python uses 'def' keyword for functions. Parameters don't require type annotations."
- id: syn_03
+ target_background: [all]
section: basic_syntax
type: multiple_choice
difficulty: basic
@@ -59,6 +62,7 @@ questions:
explanation: "Python uses indentation for code blocks, not braces. Correct: if x > 5: followed by indented block."
- id: syn_04
+ target_background: [all]
section: basic_syntax
type: fill_blank
difficulty: basic
@@ -68,6 +72,7 @@ questions:
explanation: "range(n) generates numbers 0, 1, 2, ..., n-1."
- id: syn_05
+ target_background: [javascript]
section: basic_syntax
type: multiple_choice
difficulty: intermediate
@@ -75,14 +80,15 @@ questions:
stem: "In Python, what does '==' compare?"
options:
a: "Identity (same object in memory)"
- b: "Value equality (like JavaScript's ===)"
+ b: "Value equality, including equality between some numeric types"
c: "Loose equality with type coercion"
d: "Reference equality"
correct: b
- explanation: "Python's == is value equality (no type coercion). For identity, use 'is'."
+ explanation: "Python's == invokes value equality: True == 1 and 1 == 1.0 are true, but '1' == 1 is false. It is not JavaScript ===. For identity, use 'is'."
# --- Bytes and Strings ---
- id: bytes_01
+ target_background: [all]
section: bytes_and_strings
type: multiple_choice
difficulty: intermediate
@@ -98,6 +104,7 @@ questions:
explanation: "Python sockets require bytes, not strings. Fix: sock.send(b'Hello') or sock.send('Hello'.encode('utf-8'))"
- id: bytes_02
+ target_background: [all]
section: bytes_and_strings
type: multiple_choice
difficulty: basic
@@ -112,6 +119,7 @@ questions:
explanation: "b\"...\" creates a bytes object directly."
- id: bytes_03
+ target_background: [all]
section: bytes_and_strings
type: fill_blank
difficulty: intermediate
@@ -121,20 +129,22 @@ questions:
explanation: ".decode() converts bytes → string. .encode() converts string → bytes."
- id: bytes_04
+ target_background: [c]
section: bytes_and_strings
type: multiple_choice
difficulty: intermediate
bloom_level: analyze
- stem: "What is Python's equivalent of C's htons(8080) for packing a port?"
+ stem: "Which struct call serialises port 8080 as exactly two bytes in network byte order?"
options:
a: "htons(8080)"
b: "socket.htons(8080)"
c: "struct.pack('!H', 8080)"
- d: "int.to_bytes(8080, 2, 'big')"
+ d: "struct.pack('!I', 8080)"
correct: c
- explanation: "struct.pack('!H', 8080) packs as network byte order. '!' = network order, 'H' = unsigned short."
+ explanation: "struct.pack('!H', 8080) produces two big-endian bytes. socket.htons returns an integer, not bytes. (8080).to_bytes(2, 'big') is an equivalent serialisation outside struct."
- id: bytes_05
+ target_background: [all]
section: bytes_and_strings
type: multiple_choice
difficulty: advanced
@@ -151,6 +161,7 @@ questions:
# --- Socket Programming ---
- id: sock_01
+ target_background: [all]
section: socket_programming
type: multiple_choice
difficulty: basic
@@ -165,6 +176,7 @@ questions:
explanation: "SOCK_STREAM = TCP (reliable, ordered). SOCK_DGRAM = UDP (unreliable)."
- id: sock_02
+ target_background: [all]
section: socket_programming
type: multiple_choice
difficulty: intermediate
@@ -172,13 +184,14 @@ questions:
stem: "What does SO_REUSEADDR do?"
options:
a: "Enables encryption"
- b: "Allows reusing the port immediately after server stops"
+ b: "Allows some address reuse, including typical TCP TIME_WAIT rebinding on Linux"
c: "Sets non-blocking mode"
d: "Enables broadcasting"
correct: b
- explanation: "SO_REUSEADDR allows rebinding to a port in TIME_WAIT state (no 60s wait)."
+ explanation: "SO_REUSEADDR relaxes bind address-reuse checks subject to OS rules; it does not override a conflicting active listener or guarantee a fixed wait time."
- id: sock_03
+ target_background: [all]
section: socket_programming
type: multiple_choice
difficulty: intermediate
@@ -193,6 +206,7 @@ questions:
explanation: "TCP Server: socket() → bind() → listen() → accept(). Mnemonic: BLA = Bind, Listen, Accept"
- id: sock_04
+ target_background: [all]
section: socket_programming
type: multiple_choice
difficulty: intermediate
@@ -200,13 +214,14 @@ questions:
stem: "Difference between send() and sendall()?"
options:
a: "send() is for TCP, sendall() is for UDP"
- b: "send() may send partial data, sendall() sends everything"
+ b: "send() may accept a prefix; sendall() loops until all bytes are accepted locally or an error occurs"
c: "sendall() is faster"
d: "They are identical"
correct: b
explanation: "send() might send fewer bytes (returns count). sendall() keeps sending until complete."
- id: sock_05
+ target_background: [all]
section: socket_programming
type: fill_blank
difficulty: intermediate
@@ -216,12 +231,14 @@ questions:
explanation: "recvfrom() returns (data, address) tuple — needed for UDP since it's connectionless."
- id: sock_06
+ target_background: [all]
section: socket_programming
type: multiple_choice
difficulty: intermediate
bloom_level: analyze
stem: |
- What happens when this runs?
+ On Linux with net.ipv4.ip_unprivileged_port_start=1024, port 80 free,
+ no root privileges and no CAP_NET_BIND_SERVICE, what happens here?
server = socket.socket()
server.bind(('0.0.0.0', 80))
options:
@@ -230,15 +247,16 @@ questions:
c: "Syntax error"
d: "Address already in use"
correct: b
- explanation: "Ports 0-1023 require root/admin. Use ports >= 1024 for development."
+ explanation: "Under the stated Linux policy, bind raises PermissionError. Thresholds and privileges vary by OS and container configuration; a successful bind would not yet call listen()."
- id: sock_07
+ target_background: [all]
section: socket_programming
type: multiple_choice
difficulty: advanced
bloom_level: evaluate
stem: |
- Why might this code lose data?
+ Assume the received bytes decode correctly. Why can treating this read as one complete application message be wrong?
data = sock.recv(1024)
process(data.decode())
options:
@@ -251,11 +269,12 @@ questions:
# --- Error Handling ---
- id: err_01
+ target_background: [all]
section: error_handling
type: multiple_choice
difficulty: basic
bloom_level: remember
- stem: "Exception raised when a connection is refused?"
+ stem: "Which most specific built-in exception reports a refused TCP connection?"
options:
a: "socket.error"
b: "ConnectionRefusedError"
@@ -265,6 +284,7 @@ questions:
explanation: "ConnectionRefusedError — server not listening or firewall blocked."
- id: err_02
+ target_background: [java, kotlin]
section: error_handling
type: multiple_choice
difficulty: intermediate
@@ -279,6 +299,7 @@ questions:
explanation: "Python has NO checked exceptions. All can propagate without declaration."
- id: err_03
+ target_background: [all]
section: error_handling
type: fill_blank
difficulty: basic
@@ -292,6 +313,7 @@ questions:
explanation: "Python uses 'except' (not 'catch' like Java/JS)."
- id: err_04
+ target_background: [java, kotlin]
section: error_handling
type: multiple_choice
difficulty: intermediate
@@ -306,6 +328,7 @@ questions:
explanation: "The 'with' statement (context manager) guarantees cleanup."
- id: err_05
+ target_background: [all]
section: error_handling
type: multiple_choice
difficulty: intermediate
@@ -324,6 +347,7 @@ questions:
# --- Python Idioms ---
- id: idiom_01
+ target_background: [all]
section: python_idioms
type: multiple_choice
difficulty: intermediate
@@ -338,6 +362,7 @@ questions:
explanation: "Both are valid. list(range(...)) is simpler; list comprehension is better for filtering."
- id: idiom_02
+ target_background: [all]
section: python_idioms
type: multiple_choice
difficulty: intermediate
@@ -352,6 +377,7 @@ questions:
explanation: "Python dicts use brackets: config['key']. Dot notation is for object attributes."
- id: idiom_03
+ target_background: [all]
section: python_idioms
type: fill_blank
difficulty: intermediate
@@ -361,6 +387,7 @@ questions:
explanation: "f-strings (Python 3.6+) allow inline expressions with f\"...{var}...\" syntax."
- id: idiom_04
+ target_background: [all]
section: python_idioms
type: multiple_choice
difficulty: intermediate
@@ -375,6 +402,7 @@ questions:
explanation: "Empty containers are 'falsy'. 'if not packets:' is idiomatic."
- id: idiom_05
+ target_background: [all]
section: python_idioms
type: multiple_choice
difficulty: advanced
@@ -390,6 +418,7 @@ questions:
# --- Debugging ---
- id: debug_01
+ target_background: [all]
section: debugging
type: multiple_choice
difficulty: intermediate
@@ -404,6 +433,7 @@ questions:
explanation: "'logging' module provides levels (DEBUG, INFO, WARNING, ERROR) and can be disabled."
- id: debug_02
+ target_background: [all]
section: debugging
type: fill_blank
difficulty: basic
@@ -413,6 +443,7 @@ questions:
explanation: "settimeout(seconds) makes blocking operations time out."
- id: debug_03
+ target_background: [all]
section: debugging
type: multiple_choice
difficulty: advanced
@@ -429,6 +460,7 @@ questions:
explanation: "recv() is blocking by default. Use settimeout() or non-blocking mode."
- id: debug_04
+ target_background: [all]
section: debugging
type: multiple_choice
difficulty: intermediate
diff --git a/00_APPENDIX/a)PYTHON_self_study_guide/formative/run_quiz.py b/00_APPENDIX/a)PYTHON_self_study_guide/formative/run_quiz.py
index 1ecccc8..c2551f5 100755
--- a/00_APPENDIX/a)PYTHON_self_study_guide/formative/run_quiz.py
+++ b/00_APPENDIX/a)PYTHON_self_study_guide/formative/run_quiz.py
@@ -10,7 +10,7 @@
python run_quiz.py # Full quiz
python run_quiz.py --quick # 10 random questions
python run_quiz.py --background c # C-programmer specific
- python run_quiz.py --section sockets # Topic filtering
+ python run_quiz.py --section socket # Topic filtering
Course: Computer Networks — ASE Bucharest, CSIE
Version: 5.0 — January 2026
@@ -319,17 +319,17 @@ def check_answer(question: Dict[str, Any], answer: str) -> bool:
Returns:
True if answer matches the correct answer.
"""
- correct = str(question['correct']).lower()
-
- if question.get('type') == 'fill_blank':
- # Accept partial matches for fill-in-the-blank
- acceptable = question.get('correct', [])
- if isinstance(acceptable, list):
- return any(ans.lower() in answer.lower() or answer.lower() in ans.lower()
- for ans in acceptable)
- return correct in answer.lower() or answer.lower() in correct
-
- return answer == correct
+ normalise = lambda value: str(value).strip().casefold()
+ kind = question.get('type')
+ if kind == 'true_false':
+ values = {'t': True, 'true': True, 'f': False, 'false': False}
+ expected = question['correct']
+ expected = expected if isinstance(expected, bool) else values.get(normalise(expected))
+ supplied = values.get(normalise(answer))
+ return expected is not None and supplied is not None and supplied == expected
+ acceptable = question['correct']
+ acceptable = acceptable if isinstance(acceptable, list) else [acceptable]
+ return normalise(answer) in {normalise(value) for value in acceptable}
# ═══════════════════════════════════════════════════════════════════════════════
@@ -387,7 +387,9 @@ def _show_misconception_ref(question: Dict[str, Any], is_correct: bool) -> None:
def run_quiz(
questions: List[Dict[str, Any]],
randomise: bool = False,
- limit: Optional[int] = None
+ limit: Optional[int] = None,
+ scoring: Optional[Dict[str, Any]] = None,
+ passing_score: float = 70
) -> Dict[str, Any]:
"""
Run the interactive quiz and return results.
@@ -403,6 +405,11 @@ def run_quiz(
"""
questions = _prepare_questions(questions, randomise, limit)
results = _initialise_results(len(questions))
+ results['passing_score'] = passing_score
+ weights = scoring or {}
+ results['weights'] = {q['id']: float(weights.get(q.get('difficulty', 'basic'), {}).get('weight', 1)) for q in questions}
+ results['planned_points'] = sum(results['weights'].values())
+ results['earned_points'] = 0.0
_display_quiz_header(len(questions))
@@ -415,9 +422,14 @@ def run_quiz(
if i < len(questions):
input(f"\n{Colours.DIM}Press Enter for next question...{Colours.RESET}")
- except KeyboardInterrupt:
- print(f"\n\n{Colours.YELLOW}Quiz aborted.{Colours.RESET}")
-
+ except (KeyboardInterrupt, EOFError):
+ print(f"\n\n{Colours.YELLOW}Quiz interrupted.{Colours.RESET}")
+
+ results['attempted'] = len(results['answers']) - results['skipped']
+ results['unattempted'] = results['total'] - len(results['answers'])
+ results['session_status'] = 'complete' if results['unattempted'] == 0 else 'incomplete'
+ results['percentage'] = 100 * results['earned_points'] / results['planned_points'] if results['planned_points'] else 0
+ results['passed'] = results['session_status'] == 'complete' and results['percentage'] >= passing_score
return results
@@ -484,6 +496,7 @@ def _process_question(
is_correct = check_answer(question, answer)
if is_correct:
results['correct'] += 1
+ results['earned_points'] += results['weights'][question['id']]
section = question.get('section', 'general')
results['by_section'][section]['correct'] += 1
@@ -519,8 +532,8 @@ def display_results(results: Dict[str, Any]) -> None:
"""
c = Colours
- answered = results['total'] - results['skipped']
- percentage = (results['correct'] / answered * 100) if answered > 0 else 0
+ answered = results['attempted']
+ percentage = results['percentage']
_display_results_header()
_display_overall_score(results, answered, percentage)
@@ -544,23 +557,16 @@ def _display_overall_score(
"""Display overall score with colour coding."""
c = Colours
- if percentage >= 80:
- grade_colour = c.GREEN
- emoji = '🌟'
- message = "Excellent! Ready for networking labs."
- elif percentage >= 60:
- grade_colour = c.YELLOW
- emoji = '👍'
- message = "Good progress. Review weak areas."
+ print(f" Correct answers: {results['correct']}/{answered} attempted")
+ print(f" Skipped: {results['skipped']}; unattempted: {results['unattempted']}; planned: {results['total']}")
+ print(f" Weighted score: {results['earned_points']:g}/{results['planned_points']:g} ({percentage:.1f}%)")
+ print(f" Passing threshold: {results['passing_score']:g}%")
+ if results['session_status'] != 'complete':
+ print(" Incomplete session: no readiness/pass verdict. Finish the remaining items.")
+ elif results['passed']:
+ print(" Threshold reached. Review feedback and verify the practical skills in the labs.")
else:
- grade_colour = c.RED
- emoji = '📚'
- message = "More study recommended before labs."
-
- score_text = f"{results['correct']}/{answered} ({percentage:.0f}%)"
- print(f" {emoji} Score: {grade_colour}{c.BOLD}{score_text}{c.RESET}")
- print(f" {c.DIM}Skipped: {results['skipped']}{c.RESET}")
- print(f"\n {message}\n")
+ print(" Threshold not reached. Review missed and skipped questions.")
def _display_section_breakdown(results: Dict[str, Any]) -> None:
@@ -590,7 +596,7 @@ def save_results(results: Dict[str, Any], output_dir: Path) -> Path:
Path to the saved JSON file.
"""
output_dir.mkdir(parents=True, exist_ok=True)
- timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
+ timestamp = datetime.now().strftime('%Y%m%d_%H%M%S_%f')
output_path = output_dir / f'quiz_results_{timestamp}.json'
with open(output_path, 'w', encoding='utf-8') as f:
@@ -653,6 +659,10 @@ def main() -> None:
Colours.disable()
# Normalise background
+ if args.limit is not None and args.limit <= 0:
+ parser.error('--limit must be positive')
+ if args.background == 'all':
+ args.background = None
if args.background == 'js':
args.background = 'javascript'
@@ -676,7 +686,7 @@ def main() -> None:
if not questions:
print(f"{Colours.YELLOW}No questions match the specified filters.{Colours.RESET}")
- sys.exit(0)
+ sys.exit(1)
# Determine limit
limit = args.limit
@@ -685,7 +695,9 @@ def main() -> None:
args.random = True
# Run quiz
- results = run_quiz(questions, randomise=args.random, limit=limit)
+ results = run_quiz(questions, randomise=args.random, limit=limit,
+ scoring=quiz_data.get('scoring'),
+ passing_score=quiz_data.get('metadata', {}).get('passing_score', 70))
# Display and optionally save results
display_results(results)
diff --git a/00_APPENDIX/b)optional_LECTURES/S10Theory_Application-layer_protocols_EN.html b/00_APPENDIX/b)optional_LECTURES/S10Theory_Application-layer_protocols_EN.html
index aaee81b..393b52c 100644
--- a/00_APPENDIX/b)optional_LECTURES/S10Theory_Application-layer_protocols_EN.html
+++ b/00_APPENDIX/b)optional_LECTURES/S10Theory_Application-layer_protocols_EN.html
@@ -507,7 +507,7 @@ Anatomy of an HTTP Response
The response mirrors the request structure: a status line, headers and an optional body.
HTTP/1.1 200 OK
Content-Type : application/json; charset=utf-8
-Content-Length : 128
+Content-Length : 54
Cache-Control : max-age=3600
X-Request-Id : a3f8c2d1-e9b7-4f2a
@@ -542,7 +542,7 @@
HTTP Methods: Semantics, Not Convention
Why does this table matter?
-
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 preflight OPTIONS request to ask permission.
+
https://app.example.com requests https://api.example.com — different host. A non-safelisted method or header causes a preflight OPTIONS 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.1
Upgrade : websocket
Connection : Upgrade
-Sec-WebSocket-Key : dGhlIHNh...
+Sec-WebSocket-Version : 13
+Sec-WebSocket-Key : dGhlIHNhbXBsZSBub25jZQ==
HTTP/1.1 101 Switching Protocols
Upgrade : websocket
-Connection : Upgrade
+Connection : Upgrade
+Sec-WebSocket-Accept : s3pPLMBiTxaQ9kYGzzhZRbK+xOo=
@@ -1059,17 +1061,18 @@
Level 3 — HATEOAS
Checkpoint — REST in Practice
-
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.
@@ -1163,9 +1166,10 @@
Debugging HTTP with curl
https://httpbin.org/post
-
curl -L -w
"DNS: %{time_namelookup}s\nTCP: %{time_connect}s\nTLS: %{time_appconnect}s\nTotal: %{time_total}s\n" \
+
curl -L -w
"DNS complete: %{time_namelookup}s\nTCP complete: %{time_connect}s\nTLS complete: %{time_appconnect}s\nTotal: %{time_total}s\n" \
-o /dev/null -s \
https://example.com
+
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.
Instructor note
@@ -1464,6 +1468,7 @@
Contents
// ── Keyboard Navigation ──────────────────────────────
document.addEventListener('keydown', function(e) {
+ if (e.target && e.target.closest && e.target.closest('input, textarea, select, button, [contenteditable="true"]')) return;
if (e.target.tagName === 'INPUT' || e.target.tagName === 'TEXTAREA' || e.target.tagName === 'SELECT') return;
switch(e.key) {
case 'ArrowRight': case ' ': e.preventDefault(); changeSlide(1); break;
diff --git a/00_APPENDIX/b)optional_LECTURES/S11Theory_FTP_DNS_and_SSH_EN.html b/00_APPENDIX/b)optional_LECTURES/S11Theory_FTP_DNS_and_SSH_EN.html
index 5b171a6..de24e4b 100644
--- a/00_APPENDIX/b)optional_LECTURES/S11Theory_FTP_DNS_and_SSH_EN.html
+++ b/00_APPENDIX/b)optional_LECTURES/S11Theory_FTP_DNS_and_SSH_EN.html
@@ -195,7 +195,7 @@
The Day Half the Internet Went Dark
21 October 2016
-
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);
+ }
}
+