SyntaxPilot
Courses/Cybersecurity Fundamentals/Lesson 17

Cybersecurity Fundamentals · Lesson 17 of 90 · 16 min

Networking from a security view: OSI and TCP/IP models

OSI 7 layersTCP/IP 4-layer modelencapsulationframepacketsegmentdatagramMAC addressIP addressportprotocolclient-server modelwhere each control lives in the stack

These are the notes for Cybersecurity Fundamentals (defensive), episode 17. For six episodes we protected messages with cryptography. Now we study the road those messages travel on: the network. Attackers and defenders both describe problems in layers ("a layer 2 attack", "a layer 7 firewall"), so you need the map. You'll invent each idea from a real-life problem: the protocol and the client-server model, the IP address and the port, the OSI 7 layers and the TCP/IP 4-layer model, the MAC address, encapsulation with its units (segment, datagram, packet, frame), and finally where each security control lives in the stack. Every term is explained the first time it appears, and the Glossary at the end defines them all again.

Riya, Aman, the menu, the MAC addresses (aa:01, ...) and the 10.0.0.x addresses are made up; 198.51.100.7 comes from a range reserved for documentation examples. Every program runs only on 127.0.0.1, which means "this same computer": nothing leaves your machine. Every code sample runs with Python 3.13 and only the standard library; outputs are real, copied from actual runs. The client's temporary port number (like 37430) is different on every run. In tracebacks, long file paths are shortened to main.py.

The problems you'll solve

Problem Idea it teaches
Just connect and send? Refused Protocol, server, client, client-server model
Which computer, which program? IP address, port, well-known ports
One giant program breaks on every change Layers: the OSI 7 layers, the TCP/IP 4-layer model
Who carries it to the next box? MAC address, hop, router
How do layers share one message? Encapsulation, header, segment, packet, frame
No call, just a postcard UDP datagram vs TCP segment
Attacks at every layer Where each security control lives in the stack, defence in depth

Problem 1: just connect and send?

Riya runs a chai stall. Her phone app wants today's menu from Aman's computer, where the prices are kept. The obvious first try: connect to Aman's computer and send the words GET menu.

To talk over a network, a program uses a socket: the program's handle on a network connection, like a phone handset. socket.AF_INET means "IPv4 addresses" and socket.SOCK_STREAM means TCP, the reliable way to send a stream of data (more below and in episode 19).

Demo 1: connecting when nobody is listening

import socket

# the client: Riya's app asks for the menu
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.connect(("127.0.0.1", 5050))    # nobody is listening!
c.sendall(b"GET menu")
print(c.recv(100))

Output:

Traceback (most recent call last):
  File "main.py", line 5, in <module>
    c.connect(("127.0.0.1", 5050))    # nobody is listening!
    ~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^
ConnectionRefusedError: [Errno 111] Connection refused

Why it failed: the computer exists, but no program is waiting at port 5050, so the operating system rejects the connection. You can't talk to someone who isn't listening, and even if someone were, both sides must agree on what to say.

The fix: server, client and protocol (the chai stall)

At a chai stall On a network
The stall is open all day, waiting for customers A server: a program that waits for requests and answers them
A customer walks up and starts the talk A client: a program that starts the conversation and asks
"One cutting chai" → "10 rupees" → pay: everyone knows the script A protocol: agreed rules for the format and order of messages
  • The client-server model: one server waits and serves many clients that come and ask. Your browser is a client; a website runs on a server; a banking app talks to the bank's servers.
  • A protocol is like the rules of a phone call ("Hello?" first, "Bye" last). HTTP (web pages), DNS (looking up names), TCP and IP are all protocols. Without a shared protocol, the bytes arrive but mean nothing to the other side.

Problem 2: which computer, which program?

A parcel needs a building address with a PIN code to find one building in all of India, and a flat number to find one family inside it.

Posting a parcel On a network
Building address with PIN code IP address: a number that identifies a computer on a network, like 10.0.0.9
Flat number Port: a number from 0 to 65,535 that picks one program on that computer
Building + flat IP address + port = one exact program on one exact computer
  • IP address: IPv4 (the Internet Protocol version 4, RFC 791, 1981) uses 32-bit addresses, written as four numbers from 0 to 255 separated by dots: 10.0.0.9. 127.0.0.1 is the loopback address: "this same computer". Episode 18 explains address ranges, IPv6 and more.
  • Port: one computer runs many programs at once (a web server, a database, a chat app). The port says which one. Port ranges (RFC 6335): 0-1023 system or well-known ports, 1024-49151 user or registered ports, 49152-65535 dynamic (temporary) ports. Examples: 443 HTTPS, 80 HTTP, 22 SSH, 53 DNS.
  • A server binds (claims) an address and port, then listens. A client connects to that address and port. The operating system gives the client a temporary port of its own for that one conversation.

Demo 2: a real server and client

import socket, threading

srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.bind(("127.0.0.1", 5050))    # IP address + port
srv.listen()                      # the stall opens
def server():                     # waits, then answers
    conn, addr = srv.accept()
    req = conn.recv(100)
    print("server got", req, "from", addr)
    conn.sendall(b"chai 10, samosa 15")
    conn.recv(100)                # until the client hangs up
    conn.close()

threading.Thread(target=server).start()
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.connect(("127.0.0.1", 5050))   # the client starts
c.sendall(b"GET menu")
print("client got", c.recv(100))
c.close()

Output:

server got b'GET menu' from ('127.0.0.1', 37430)
client got b'chai 10, samosa 15'

How it works, line by line:

  • bind claims 127.0.0.1:5050; listen opens the stall; accept waits until a client arrives and returns a new connection conn plus the client's address.
  • A thread (a second line of work inside the same program) runs server() at the same time as the client code, so one script can play both roles.
  • The client's address ('127.0.0.1', 37430) shows that both ends of a conversation have an IP address and a port. 37430 was picked by the operating system.
  • b"GET menu" is bytes, not text. Networks carry bytes: raw numbers from 0 to 255. (conn.recv(100) before close makes the server wait for the client to hang up first; see the "Address already in use" mistake below for why.)

Problem 3: one giant program breaks

Imagine Riya's app had to do everything itself: turn bytes into radio signals, find a route across cities, resend lost pieces, and show the menu. She swaps Wi-Fi for a cable and the whole app breaks. Every app would need rewriting for every new kind of wire.

The fix: layers. Split the job so that each layer does one job and only talks to the layer just below it. Change the wire, and only the bottom layer changes. A courier company works the same way.

Sending Diwali sweets from Pune to Delhi Network layer
Your note: "Happy Diwali!" (you only care about the words) Application: the actual message (HTTP, DNS)
Boxes numbered "1 of 2", "2 of 2", for flat 5050; a lost box is resent Transport: program to program, ports, reliability (TCP, UDP)
Address label with PIN code, sorted hub to hub across India Network (internet): IP addresses and routing (choosing the path)
A delivery bike carries it one short trip to the next hub, on real roads Link (Ethernet, Wi-Fi, MAC addresses) on top of physical (cables, radio)

The OSI model: 7 layers

The OSI model (Open Systems Interconnection) is the textbook reference model, published by ISO as ISO 7498 in 1984 and revised as ISO/IEC 7498-1 in 1994. Numbered from the bottom:

# OSI layer Its job in plain words Examples
7 Application What the user's program says HTTP, DNS, SMTP (email)
6 Presentation Data format: encoding, compression UTF-8 text, JPEG, gzip
5 Session Start, keep and end a conversation Logins that stay open, resuming a call
4 Transport Program to program, ports, reliability TCP, UDP
3 Network Computer to computer across networks; routing IP, ICMP
2 Data link Next box on the same link; frames, MAC addresses Ethernet, Wi-Fi
1 Physical Bits as voltage, light or radio Copper cable, fibre, radio waves

Memory trick, layers 1 to 7: "Please Do Not Throw Sausage Pizza Away" (Physical, Data link, Network, Transport, Session, Presentation, Application).

The TCP/IP model: 4 layers (what really runs)

The internet runs the simpler TCP/IP model, described in RFC 1122 (October 1989) with four layers:

TCP/IP layer Matches OSI Examples
Application 5, 6, 7 HTTP, DNS, SSH (TLS sits just above TCP)
Transport 4 TCP ("reliable, connection-oriented"), UDP ("connectionless datagram")
Internet 3 IP carries data from source host to destination host; ICMP
Link 1, 2 Ethernet, Wi-Fi, MAC addresses
  • TCP first sets up a connection, numbers the data, resends what's lost and keeps it in order.
  • UDP has no connection: it just sends each message on its own.
  • A host is any computer on a network: a phone, a laptop, a server.
  • OSI is the map people use to talk about problems and products; TCP/IP is the stack (the set of layers) actually running in your phone.

Problem 4: who carries it to the next box? The MAC address

The IP address says the final destination. But the bike only goes to the next hub. At each hub a new local slip is written: "to Mumbai, dock 4". The PIN-code label never changes.

  • A hop is one trip between two directly connected devices (your laptop to your Wi-Fi router, one router to the next).
  • A MAC address (media access control address) is the local, link-layer address used for that hop. It is 48 bits, set in the network card, written as six pairs of hexadecimal digits (0-9 and a-f), like aa:bb:cc:11:22:33. The first 24 bits usually identify the maker.
  • A router is the box that joins networks and forwards packets. At every hop the MAC addresses are rewritten, while the IP addresses stay the same from start to end.
  • Security note: the MAC address only matters on the local network, and software can change it (it can be faked), so it is never proof of identity on its own.
MAC address IP address Port
Layer (TCP/IP) Link Internet Transport
Identifies A network card on this link A computer (host) A program on that host
Size 48 bits 32 bits (IPv4) 16 bits (0-65,535)
Changes on each hop? Yes No (except NAT, episode 18) No (except NAT)
Real-life Local slip "to dock 4" PIN-code address Flat number

Problem 5: envelopes inside envelopes (encapsulation)

How do the layers share one message without stepping on each other? Each layer wraps what it got from above in its own envelope, with its own label on the front called a header (and sometimes a label at the back called a trailer). This wrapping is encapsulation. The receiver does the opposite: each layer removes its own header and hands the rest up (decapsulation). A layer never opens the inner envelopes.

Layer adds The unit is called
(the app's message) data
TCP header with ports segment
UDP header with ports datagram
IP header with IP addresses packet (IP's unit is also called an IP datagram)
Ethernet/Wi-Fi header + trailer with MAC addresses and a check value frame
Sent on the wire bits

The frame's trailer is the FCS (frame check sequence): a checksum the receiver recomputes to detect bits damaged on the way.

Demo 3: the obvious way fails (text + bytes)

data = b"GET menu"                        # application
seg = "[TCP 49152>5050]" + data           # transport
print(seg)

Output:

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    seg = "[TCP 49152>5050]" + data           # transport
          ~~~~~~~~~~~~~~~~~~~^~~~~~
TypeError: can only concatenate str (not "bytes") to str

Why: Python text (str) and raw bytes (bytes) don't mix. Below the application, every layer handles bytes, so every header must be bytes too.

Demo 4: encapsulation by hand

Toy headers, readable on purpose. Real headers are binary with fixed sizes (an IPv4 header is at least 20 bytes, a TCP header at least 20), but the idea is identical.

data = b"GET menu"                            # application
seg = b"[TCP 49152>5050]" + data              # transport
pkt = b"[IP 10.0.0.5>10.0.0.9]" + seg         # network
frm = b"[ETH aa>bb]" + pkt + b"[FCS]"         # data link

for name, unit in [("data", data), ("segment", seg),
                   ("packet", pkt), ("frame", frm)]:
    print(f"{name:8}{len(unit):3}  {unit.decode()}")

# the receiver peels off one header per layer
p = frm.removeprefix(b"[ETH aa>bb]").removesuffix(b"[FCS]")
s = p.removeprefix(b"[IP 10.0.0.5>10.0.0.9]")
print("app reads:", s.removeprefix(b"[TCP 49152>5050]"))

Output:

data      8  GET menu
segment  24  [TCP 49152>5050]GET menu
packet   46  [IP 10.0.0.5>10.0.0.9][TCP 49152>5050]GET menu
frame    62  [ETH aa>bb][IP 10.0.0.5>10.0.0.9][TCP 49152>5050]GET menu[FCS]
app reads: b'GET menu'

Security view: every device on the path can read the IP addresses and ports (it needs them to deliver the frame), and, without encryption, it can also read GET menu. Reading traffic on a network is called sniffing. TLS (episode 22) encrypts the application data, but the IP and TCP headers stay visible: an observer still learns who talks to whom, on which port, and how much.

Problem 6: segments and datagrams (TCP vs UDP)

TCP first sets up a connection, like a phone call, then sends a numbered stream of segments. UDP skips the call: each message is one datagram, a self-contained message sent on its own, like a postcard dropped in a post box. UDP is fast and simple (live video, online games, DNS lookups), but nothing promises delivery.

Demo 5: a UDP datagram, even to nobody

SOCK_DGRAM means UDP. sendto sends one datagram to an address; recvfrom receives one datagram and the sender's address.

import socket

rx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
rx.bind(("127.0.0.1", 6060))           # the receiver

tx = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
n = tx.sendto(b"score 4/0", ("127.0.0.1", 7070))
print("sent", n, "bytes to 7070 (nobody there!)")

tx.sendto(b"score 120/2", ("127.0.0.1", 6060))
msg, addr = rx.recvfrom(100)           # one whole datagram
print("6060 got", msg, "from", addr)

Output:

sent 9 bytes to 7070 (nobody there!)
6060 got b'score 120/2' from ('127.0.0.1', 35891)

No error for port 7070, where nobody listens: with TCP that was ConnectionRefusedError. UDP just lets it go. The datagram to 6060 arrives whole, as one message.

TCP UDP
Connection first? Yes (handshake, episode 19) No
Unit Segment (a stream) Datagram (one message)
Delivery and order Guaranteed: resends, keeps order Not guaranteed
Speed / overhead More work Fast, small header
Used by HTTP/1.1 and HTTP/2, SSH, email DNS, live video, games, HTTP/3 (over QUIC)

Problem 7: where each control lives in the stack

Every layer can be attacked, so every layer gets its own defence. These are concepts for defenders; the attack names are explained properly in later episodes.

Layer What can go wrong (concept) Security controls that live here
1 Physical Cable tapped, laptop or disk stolen, cable cut Locked server rooms, cameras, disk encryption
2 Data link Unknown device plugs into the office network; fake MAC addresses Switch port security, 802.1X (only approved devices join), WPA3 for Wi-Fi
3 Network (internet) Traffic arrives from anywhere; fake source IPs Firewall rules on IP addresses, network segmentation, IPsec VPNs
4 Transport Unused ports left open; floods of connection attempts Close unused ports, firewall rules on ports, rate limits
Above TCP Readable data (sniffing) TLS encrypts and authenticates (HTTPS)
7 Application Bad input, weak logins, stolen sessions Input validation, authentication, authorization, WAF (web application firewall)
  • A firewall is a filter that allows or blocks traffic by rules. A classic firewall reads layer 3 and 4 headers (IP addresses, ports); a WAF reads layer 7 (the HTTP request itself).
  • Defence in depth (episode 3): a check at every layer, so an attack that slips past one layer is caught at another.

Demo 6: a toy layered checker

A toy model to see the idea, never a real firewall. Each request is a tuple: MAC address, IP address, port, data. check(*p) passes the four parts of the tuple as four arguments.

KNOWN_MACS = {"aa:01", "aa:02"}       # devices we own

def check(mac, ip, port, data):        # defence in depth
    if mac not in KNOWN_MACS:
        return "blocked at L2: unknown device"
    if not ip.startswith("10."):
        return "blocked at L3: not our network"
    if port != 443:
        return "blocked at L4: port closed"
    if "../" in data:
        return "blocked at L7: bad input"
    return "allowed"

for p in [("aa:01", "10.0.0.5", 443, "GET /menu"),
          ("ff:66", "10.0.0.7", 443, "GET /menu"),
          ("aa:02", "198.51.100.7", 443, "GET /"),
          ("aa:02", "10.0.0.6", 23, "login"),
          ("aa:01", "10.0.0.5", 443, "GET /../etc")]:
    print(f"{p[1]:13}:{p[2]:<4} {check(*p)}")

Output:

10.0.0.5     :443  allowed
10.0.0.7     :443  blocked at L2: unknown device
198.51.100.7 :443  blocked at L3: not our network
10.0.0.6     :23   blocked at L4: port closed
10.0.0.5     :443  blocked at L7: bad input

Port 23 is Telnet, an old remote-login protocol that sends everything, passwords included, unencrypted. ../ ("go up one folder") in a path is a classic sign of someone trying to read files outside the allowed folder (path traversal, a later episode). Each bad request slipped past some layers and was caught at another.

The next problem

We used addresses like 10.0.0.5 and 127.0.0.1, and our checker guessed "our network" with startswith("10."), which is crude. Who hands out addresses, what do the numbers mean, how does a packet find its way across cities, and how do fifty phones at home share one public address? Next episode: IP addressing, subnets, routing and NAT.

The whole chain

# Problem What you invented
1 Connecting to nobody is refused Server, client, client-server model, protocol
2 Which computer, which program? IP address + port
3 One giant program breaks on every change Layers: OSI 7, TCP/IP 4
4 Who carries it to the next box? MAC address, hops, routers
5 Layers share one message Encapsulation: segment, packet, frame
6 No call, just a postcard UDP datagram
7 Attacks at every layer A control at every layer (defence in depth)
? Where do addresses come from? IP addressing, subnets, routing, NAT (episode 18)

Common mistakes (and what they print)

Mistake What you see Why Fix
connect() before any server listens ConnectionRefusedError: [Errno 111] Connection refused No program at that port Start the server first: bind, listen, accept
"[TCP ...]" + b"GET menu" TypeError: can only concatenate str (not "bytes") to str Networks carry bytes, not text Use b"...", or .encode() / .decode() at the edges
sendall("GET menu") with a str TypeError: a bytes-like object is required, not 'str' Same: sockets send bytes sendall("GET menu".encode())
Restarting a server right after its side closed the connection first OSError: [Errno 98] Address already in use The old connection is still finishing closing on that port Let the client close first, wait about a minute, or use another port
UDP sendto() and assuming it arrived No error at all UDP has no delivery promise Have the app send a reply/acknowledgement, or use TCP
Binding a test server to 0.0.0.0 Reachable from other computers on the network 0.0.0.0 means "all my network interfaces" Bind to 127.0.0.1 for anything only this computer needs
Trusting a MAC address as identity Spoofed device gets in MAC addresses can be changed in software 802.1X with real credentials

The real Address already in use traceback, from preparing Demo 2 when the server closed first:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    srv.bind(("127.0.0.1", 5050))    # IP address + port
    ~~~~~~~~^^^^^^^^^^^^^^^^^^^^^
OSError: [Errno 98] Address already in use

Mini project: a tiny menu protocol

Design your own protocol: one request per line, three commands, and every unknown input rejected (an application-layer control). The server is a client-server pair on 127.0.0.1.

import socket, threading

PRICES = {"chai": 10, "samosa": 15, "vada pav": 20}

def handle(line):                      # the protocol, in one place
    parts = line.split(" ", 1)
    if parts[0] == "MENU":
        return ", ".join(PRICES)
    if parts[0] == "PRICE" and len(parts) == 2:
        item = parts[1]
        if item in PRICES:
            return f"OK {PRICES[item]}"
        return "ERR no such item"
    return "ERR unknown command"       # never trust input

srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.bind(("127.0.0.1", 5051))
srv.listen()

def server():
    conn, addr = srv.accept()
    buf = b""
    while True:
        chunk = conn.recv(100)
        if not chunk:                  # client hung up
            break
        buf += chunk
        while b"\n" in buf:            # one request per line
            line, buf = buf.split(b"\n", 1)
            reply = handle(line.decode("utf-8", "replace"))
            conn.sendall(reply.encode() + b"\n")
    conn.close()

t = threading.Thread(target=server)
t.start()

c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.connect(("127.0.0.1", 5051))
f = c.makefile("rwb")
for req in ["MENU", "PRICE chai", "PRICE pizza", "DROP TABLE", "PRICE"]:
    f.write(req.encode() + b"\n")
    f.flush()
    print(f"{req:12} -> {f.readline().decode().strip()}")
f.close()
c.close()
t.join()

Output:

MENU         -> chai, samosa, vada pav
PRICE chai   -> OK 10
PRICE pizza  -> ERR no such item
DROP TABLE   -> ERR unknown command
PRICE        -> ERR unknown command

Why the newline: TCP is a stream, not separate messages, so a protocol must say where one request ends. Here, each request ends with \n. makefile lets the client read one line at a time. Extend it: add ORDER chai 2 that replies with a total, and reject quantities above 20.

Practice

1. Make the server answer three clients, one after another.

Solution
import socket, threading

srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.bind(("127.0.0.1", 5052))
srv.listen()

def server():
    for i in range(3):                  # serve three customers
        conn, addr = srv.accept()
        name = conn.recv(100).decode()
        conn.sendall(f"token {i + 1} for {name}".encode())
        conn.recv(100)                  # wait for the client to hang up
        conn.close()

t = threading.Thread(target=server)
t.start()
for name in ["Riya", "Aman", "Meera"]:
    c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    c.connect(("127.0.0.1", 5052))
    c.sendall(name.encode())
    print(c.recv(100).decode())
    c.close()
t.join()

Output:

token 1 for Riya
token 2 for Aman
token 3 for Meera

2. Encapsulate a UDP datagram instead of a TCP segment, and work out how much of the frame is headers.

Solution
data = b"score 120/2"                         # application
dgram = b"[UDP 50000>6060]" + data            # transport: a datagram
pkt = b"[IP 10.0.0.5>10.0.0.9]" + dgram       # network
frm = b"[ETH aa>bb]" + pkt + b"[FCS]"         # data link

for name, unit in [("data", data), ("datagram", dgram),
                   ("packet", pkt), ("frame", frm)]:
    print(f"{name:9}{len(unit):3}  {unit.decode()}")
overhead = len(frm) - len(data)
print(f"headers: {overhead} of {len(frm)} bytes = {overhead / len(frm):.0%}")

Output:

data      11  score 120/2
datagram  27  [UDP 50000>6060]score 120/2
packet    49  [IP 10.0.0.5>10.0.0.9][UDP 50000>6060]score 120/2
frame     65  [ETH aa>bb][IP 10.0.0.5>10.0.0.9][UDP 50000>6060]score 120/2[FCS]
headers: 54 of 65 bytes = 83%

Small messages spend most of their bytes on headers. That's one reason chatty protocols batch data.

3. Add a layer 1 check (the device must be in a locked room) and a "TLS required" check to the toy checker.

Solution
KNOWN_MACS = {"aa:01", "aa:02"}
LOCKED_ROOMS = {"server-room"}

def check(room, mac, ip, port, tls, data):
    if room not in LOCKED_ROOMS:
        return "blocked at L1: device not in a locked room"
    if mac not in KNOWN_MACS:
        return "blocked at L2: unknown device"
    if not ip.startswith("10."):
        return "blocked at L3: not our network"
    if port != 443:
        return "blocked at L4: port closed"
    if not tls:
        return "blocked: plaintext, TLS required"
    if "../" in data:
        return "blocked at L7: bad input"
    return "allowed"

for p in [("server-room", "aa:01", "10.0.0.5", 443, True, "GET /menu"),
          ("corridor", "aa:01", "10.0.0.5", 443, True, "GET /menu"),
          ("server-room", "aa:02", "10.0.0.6", 443, False, "GET /menu")]:
    print(f"{p[0]:12} {check(*p)}")

Output:

server-room  allowed
corridor     blocked at L1: device not in a locked room
server-room  blocked: plaintext, TLS required

4. Put each thing in its TCP/IP layer: Wi-Fi, port, DNS, IP address, UDP.

Solution
LAYER = {"Ethernet": "Link", "Wi-Fi": "Link", "MAC address": "Link",
         "IP": "Internet", "IP address": "Internet",
         "TCP": "Transport", "UDP": "Transport", "port": "Transport",
         "HTTP": "Application", "DNS": "Application", "SSH": "Application"}
for thing in ["Wi-Fi", "port", "DNS", "IP address", "UDP"]:
    print(f"{thing:11} -> {LAYER[thing]} layer")

Output:

Wi-Fi       -> Link layer
port        -> Transport layer
DNS         -> Application layer
IP address  -> Internet layer
UDP         -> Transport layer

5. Why can a MAC address not be trusted as proof of who a device is?

Solution

It is only seen on the local link, it is rewritten at every hop, and the operating system can set any value on most network cards. A device can simply claim an approved MAC address. Real access control on the link layer uses 802.1X with credentials or certificates, not the MAC address alone.

Quick quiz

A firewall rule blocks all traffic to port 23 (Telnet). Which TCP/IP layer's header holds the port number this rule reads?

  • A. Link
  • B. Internet
  • C. Transport
  • D. Application
Answer

C. Transport. Port numbers live in the TCP or UDP header, which the transport layer adds. IP addresses are in the internet layer's header, MAC addresses in the link layer's.

Interview questions

  1. Name the OSI layers and give an example protocol for each. Physical (cables, radio), Data link (Ethernet, Wi-Fi), Network (IP), Transport (TCP, UDP), Session (session management), Presentation (encoding, compression), Application (HTTP, DNS).
  2. How does the TCP/IP model map to OSI? Application = OSI 5-7, Transport = 4, Internet = 3, Link = 1-2.
  3. What is encapsulation? Each layer adds its own header (and the link layer a trailer) around the data from the layer above; the receiver removes them in reverse. Data → segment/datagram → packet → frame → bits.
  4. MAC address vs IP address? MAC: 48-bit link-layer address for the next hop on the local network, rewritten at every hop. IP: internet-layer address of the source and final destination host, unchanged end to end (except through NAT).
  5. What is a port, and why do we need it? A 16-bit number identifying a program (service) on a host, so one IP address can serve many programs. Well-known: 22 SSH, 53 DNS, 80 HTTP, 443 HTTPS.
  6. TCP vs UDP? TCP: connection, ordered, reliable stream of segments. UDP: connectionless datagrams, no delivery guarantee, lower overhead.
  7. At which layer does a stateless firewall work, and a WAF? Layers 3-4 (IP addresses, ports); a WAF works at layer 7 (HTTP requests).
  8. What does an observer still see when traffic uses TLS? IP addresses, ports, packet sizes and timing: who talks to whom and how much, but not the encrypted content.

Glossary

Term Meaning in plain words Example
Network Computers connected so they can send each other data Your home Wi-Fi
Socket A program's handle on one network connection, like a phone handset socket.socket(...)
Protocol Agreed rules for the format and order of messages HTTP, TCP, "one cutting chai → 10 rupees"
Server A program that waits for requests and answers them The chai stall; a web server
Client A program that starts a conversation and asks Riya's app; your browser
Client-server model Servers wait and serve, many clients come and ask Browser ↔ website
IP address A number identifying a computer on a network 10.0.0.9
IPv4 Internet Protocol version 4, 32-bit addresses (RFC 791, 1981) 192.168.1.10
Loopback (127.0.0.1) The address meaning "this same computer" All demos in this episode
Port A number (0-65,535) picking one program on a computer 443 = HTTPS
Well-known port Ports 0-1023, reserved for standard services 22 SSH, 53 DNS, 80 HTTP
Temporary (ephemeral) port A port the OS gives a client for one conversation 37430 in Demo 2
Bind / listen / accept / connect Claim an address+port / open for clients / take one client / reach a server Demo 2
Bytes Raw data, each a number from 0 to 255; what networks carry b"GET menu"
Thread A second line of work running inside the same program The server in Demo 2
Host Any computer on a network Phone, laptop, server
Layer One part of the networking job, using only the layer below it Transport layer
Stack The set of layers working together The TCP/IP stack in your phone
OSI model 7-layer reference model (ISO 7498, 1984; ISO/IEC 7498-1, 1994) "A layer 7 attack"
Physical layer (L1) Bits as voltage, light or radio Cables, fibre, radio
Data link layer (L2) Delivers frames to the next box on the same link Ethernet, Wi-Fi
Network layer (L3) Delivers packets computer to computer across networks IP
Transport layer (L4) Program to program, ports, reliability TCP, UDP
Session layer (L5) Starts, keeps and ends conversations A login session
Presentation layer (L6) Data format, encoding, compression UTF-8, JPEG
Application layer (L7) What the user's program says HTTP, DNS
TCP/IP model The 4-layer model the internet runs (RFC 1122, 1989) Link, Internet, Transport, Application
TCP Reliable, connection-based transport protocol Web pages, SSH
UDP Connectionless transport: each message sent on its own DNS, games, video calls
HTTP / HTTPS The web's application protocol / HTTP over TLS GET /menu
DNS The protocol that turns names into IP addresses syntaxpilot.in → an IP
SSH Encrypted remote login protocol, port 22 Admins logging into servers
Ethernet The common wired link-layer technology Office LAN cables
Routing Choosing the path a packet takes across networks Pune hub → Mumbai → Delhi
Router A device that joins networks and forwards packets Your home Wi-Fi router
Hop One trip between two directly connected devices Laptop → home router
MAC address 48-bit link-layer address of a network card aa:bb:cc:11:22:33
Hexadecimal Base-16 digits: 0-9 and a-f ff = 255
Header Information a layer adds in front of the data [TCP 49152>5050]
Trailer Information added at the end [FCS]
Encapsulation Each layer wrapping the data in its own header going down Demo 4
Decapsulation Each layer removing its own header going up removeprefix in Demo 4
Data The application's message before any headers b"GET menu"
Segment TCP's unit: TCP header + data [TCP ...]GET menu
Datagram A self-contained message sent on its own (UDP's unit; also used for IP) b"score 120/2" in Demo 5
Packet The network layer's unit: IP header + segment or datagram [IP ...][TCP ...]GET menu
Frame The link layer's unit: header + packet + trailer Demo 4's 62 bytes
FCS (frame check sequence) A checksum at the end of a frame to detect damaged bits [FCS]
Sniffing Reading traffic as it passes on a network Seeing GET menu in a frame
Firewall A filter that allows or blocks traffic by rules Block port 23
WAF Web application firewall: filters HTTP requests at layer 7 Blocking ../ in paths
Port security / 802.1X Link-layer controls that let only approved devices join Office switch ports
WPA3 Current Wi-Fi security standard (episode 25) Home router setting
IPsec / VPN Encryption at the network layer / an encrypted tunnel between networks (episode 25) Office-to-office link
TLS Encryption and authentication above TCP (episode 22) The padlock in HTTPS
Telnet Old remote-login protocol on port 23, unencrypted Should be closed
Defence in depth Several independent checks, one at each layer (episode 3) Demo 6

Summary

  • A protocol is agreed rules for messages; in the client-server model a server waits and a client asks. Connecting to a port nobody listens on gives ConnectionRefusedError.
  • IP address = which computer (building with PIN code); port = which program (flat number); 127.0.0.1 = this computer.
  • The job is split into layers. OSI has 7 (Physical, Data link, Network, Transport, Session, Presentation, Application); TCP/IP has 4 (Link, Internet, Transport, Application).
  • MAC addresses carry a frame one hop; they're rewritten at every hop while IP addresses stay the same.
  • Encapsulation: data → segment (TCP) or datagram (UDP) → packet (IP) → frame (link) → bits. Networks carry bytes.
  • Every device on the path can read headers, and without encryption the data too.
  • Every layer has its own attacks and its own controls: locked rooms (L1), port security/802.1X/WPA3 (L2), firewalls/IPsec (L3-L4), TLS above TCP, validation/authentication/WAF (L7). Together: defence in depth.

Next episode: IP addressing, subnets, routing and NAT: IPv4 and IPv6, CIDR notation, subnet masks, private ranges, loopback, default gateways, NAT, ARP, ICMP and DHCP.

Sources: ISO/IEC 7498-1:1994, second edition (preview, iTeh Standards), replacing ISO 7498:1984; RFC 1122, Requirements for Internet Hosts - Communication Layers (October 1989, R. Braden, ed.), section 1.1.3; RFC 791, Internet Protocol (September 1981), via ipfyi.com; RFC 6335 section 6 port ranges, as summarised on Wikipedia "Registered port"; MAC-48/EUI-48 structure from "On MACs and EUIs" (helpful.knobs-dials.com). Code outputs from Python 3.13. Fetched 30 Oct 2026.