VLANs
A VLAN (Virtual LAN) splits one physical switch into several separate logical networks. Ports in VLAN 10 can only talk to other ports in VLAN 10 at layer 2; to reach VLAN 20, traffic must go through a router. Each VLAN is its own broadcast domain.
Why bother? A company might put staff PCs, VoIP phones, guest Wi-Fi and servers on the same switches, but in different VLANs, so that:
- broadcasts from one group don't disturb the others,
- a firewall/router between VLANs can control who reaches what (guests can't reach servers),
- moving a person to another department is a configuration change, not a re-cabling job.
Access and trunk ports
| Port type | Carries | Typical use |
|---|---|---|
| Access port | one VLAN, frames untagged | a PC, printer or phone |
| Trunk port | many VLANs, frames tagged with their VLAN ID | switch-to-switch and switch-to-router links |
The end devices never see VLAN tags. The switch adds a tag when a frame leaves on a trunk, and removes it when the frame leaves on an access port.
The 802.1Q tag
IEEE 802.1Q inserts a 4-byte tag between the source MAC and the EtherType:
| Dst MAC | Src MAC | 0x8100 | PCP(3) DEI(1) VID(12) | EtherType | Payload | FCS |
<------- 4-byte tag ------------>- TPID
0x8100says "a VLAN tag follows". - PCP (3 bits): priority 0–7 for quality of service (voice traffic usually gets 5).
- DEI (1 bit): drop eligible.
- VID (12 bits): the VLAN ID, 1–4094 (0 and 4095 are reserved).
import struct
def build_tag(vlan_id, priority=0, dei=0):
tci = (priority << 13) | (dei << 12) | vlan_id
return struct.pack("!HH", 0x8100, tci)
def parse_tag(tag):
tpid, tci = struct.unpack("!HH", tag)
return {"tpid": hex(tpid), "priority": tci >> 13, "dei": (tci >> 12) & 1, "vlan": tci & 0x0FFF}
for vid, pcp in [(10, 0), (20, 5), (4094, 7)]:
tag = build_tag(vid, pcp)
print(tag.hex(" "), parse_tag(tag))81 00 00 0a {'tpid': '0x8100', 'priority': 0, 'dei': 0, 'vlan': 10}
81 00 a0 14 {'tpid': '0x8100', 'priority': 5, 'dei': 0, 'vlan': 20}
81 00 ef fe {'tpid': '0x8100', 'priority': 7, 'dei': 0, 'vlan': 4094}
Tagging and untagging a frame
import struct
def add_tag(frame, vlan_id):
return frame[:12] + struct.pack("!HH", 0x8100, vlan_id) + frame[12:]
def remove_tag(frame):
tpid, tci = struct.unpack("!HH", frame[12:16])
assert tpid == 0x8100
return tci & 0x0FFF, frame[:12] + frame[16:]
untagged = bytes.fromhex("ffffffffffff 3c22fb910a7e 0806".replace(" ", "")) + b"ARP..."
tagged = add_tag(untagged, 20)
print("untagged:", untagged[:14].hex(" "))
print("tagged: ", tagged[:18].hex(" "))
vid, restored = remove_tag(tagged)
print("vlan", vid, "restored ok:", restored == untagged)
print("sizes:", len(untagged), "->", len(tagged))untagged: ff ff ff ff ff ff 3c 22 fb 91 0a 7e 08 06
tagged: ff ff ff ff ff ff 3c 22 fb 91 0a 7e 81 00 00 14 08 06
vlan 20 restored ok: True
sizes: 20 -> 24
The tag adds 4 bytes, which is why switches accept frames up to 1522 bytes on trunks.
A VLAN-aware switch
Let's extend the MAC learning switch: each port belongs to a VLAN (or is a trunk carrying all of them), the MAC table is keyed by (VLAN, MAC), and flooding stays inside the frame's VLAN.
BROADCAST = "ff"
class VlanSwitch:
def __init__(self, access, trunks):
self.access = access # port -> vlan
self.trunks = trunks # list of trunk ports
self.table = {} # (vlan, mac) -> port
def ports_in(self, vlan):
return [p for p, v in self.access.items() if v == vlan] + self.trunks
def receive(self, port, src, dst, tag=None):
vlan = self.access.get(port, tag)
self.table[(vlan, src)] = port
out = self.table.get((vlan, dst)) if dst != BROADCAST else None
targets = [out] if out else [p for p in self.ports_in(vlan) if p != port]
shown = [f"{p}{'(tagged)' if p in self.trunks else ''}" for p in targets]
print(f"vlan {vlan}: {src} -> {dst} from port {port}: out {', '.join(shown)}")
sw = VlanSwitch(access={1: 10, 2: 10, 3: 20, 4: 20, 5: 30}, trunks=[24])
sw.receive(1, "pc1", BROADCAST) # VLAN 10 broadcast
sw.receive(3, "phone3", BROADCAST) # VLAN 20 broadcast
sw.receive(2, "pc2", "pc1") # known destination in VLAN 10
sw.receive(5, "guest5", "pc1") # guest VLAN cannot find pc1
sw.receive(24, "srv9", BROADCAST, tag=20) # tagged frame arriving on the trunkvlan 10: pc1 -> ff from port 1: out 2, 24(tagged)
vlan 20: phone3 -> ff from port 3: out 4, 24(tagged)
vlan 10: pc2 -> pc1 from port 2: out 1
vlan 30: guest5 -> pc1 from port 5: out 24(tagged)
vlan 20: srv9 -> ff from port 24: out 3, 4
Notice the guest in VLAN 30: even though it addressed pc1 directly, the switch only searched VLAN 30, didn't find it, and flooded inside VLAN 30 (to the trunk). The PCs in VLAN 10 never saw the frame.
Routing between VLANs
Hosts in different VLANs are in different IP subnets and need a router, either:
- Router on a stick: one router interface on a trunk with a sub-interface per VLAN (
eth0.10,eth0.20), or - Layer 3 switch: the switch itself routes between VLAN interfaces (SVIs) in hardware.
On Linux you can create a VLAN sub-interface like this:
sudo ip link add link eth0 name eth0.20 type vlan id 20
sudo ip addr add 192.168.20.1/24 dev eth0.20
sudo ip link set eth0.20 up
ip -d link show eth0.20Sample output:
5: eth0.20@eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP mode DEFAULT group default qlen 1000
link/ether 3c:22:fb:91:0a:7e brd ff:ff:ff:ff:ff:ff promiscuity 0
vlan protocol 802.1Q id 20 <REORDER_HDR>Note: VLANs separate traffic, but they are not a strong security boundary on their own. Misconfigured trunks allow VLAN hopping attacks (for example double tagging through the native VLAN). Best practice: don't use VLAN 1, set an unused native VLAN, and turn off automatic trunk negotiation on access ports.
Go further: VLAN Hopping and How to Prevent It simulates switch spoofing and double tagging.
Test yourself
How many bits does the VLAN ID field have?
- 8
- 12
- 16
- 32
What kind of switch port carries frames for many VLANs with 802.1Q tags?
- Access port
- Trunk port
- Console port
- Mirror port
A PC in VLAN 10 wants to reach a server in VLAN 20. What is needed?
- Nothing, they share a switch
- A router or layer 3 switch
- A hub
- A bigger MAC table