Switching & MAC Learning
A switch connects many devices in one LAN and forwards each frame only to the port where its destination lives. Nobody configures this: the switch learns where every MAC address is by watching the traffic. This lesson simulates exactly how that works.
The three rules
For each frame that arrives on a port, a switch does:
- Learn: record "source MAC → arrival port" in its MAC address table (also called the CAM table).
- Forward or filter: look up the destination MAC.
- Known, on another port → send it out of that port only (forward).
- Known, on the same port it came from → drop it (filter).
- Flood: if the destination is unknown, or is broadcast/multicast, send it out of every port except the one it came in on.
A learning switch in Python
BROADCAST = "ff:ff:ff:ff:ff:ff"
class Switch:
def __init__(self, name, ports):
self.name = name
self.ports = ports
self.table = {} # MAC -> port
def receive(self, port, src, dst):
learned = src not in self.table
self.table[src] = port # rule 1: learn
if dst != BROADCAST and dst in self.table:
out = self.table[dst]
action = "filter" if out == port else f"forward to port {out}"
else:
out_ports = [p for p in self.ports if p != port]
action = f"flood to {out_ports}"
note = " (learned)" if learned else ""
print(f" port {port}: {src[-2:]} -> {dst[-2:]}: {action}{note}")
sw = Switch("SW1", ports=[1, 2, 3, 4])
A, B, C = "aa:aa:aa:aa:aa:01", "aa:aa:aa:aa:aa:02", "aa:aa:aa:aa:aa:03"
print("A sends to B (B unknown):")
sw.receive(1, A, B)
print("B replies to A:")
sw.receive(2, B, A)
print("A sends to B again:")
sw.receive(1, A, B)
print("C broadcasts:")
sw.receive(3, C, BROADCAST)
print("MAC table:")
for mac, port in sw.table.items():
print(f" {mac} port {port}")A sends to B (B unknown):
port 1: 01 -> 02: flood to [2, 3, 4] (learned)
B replies to A:
port 2: 02 -> 01: forward to port 1 (learned)
A sends to B again:
port 1: 01 -> 02: forward to port 2
C broadcasts:
port 3: 03 -> ff: flood to [1, 2, 4] (learned)
MAC table:
aa:aa:aa:aa:aa:01 port 1
aa:aa:aa:aa:aa:02 port 2
aa:aa:aa:aa:aa:03 port 3
The first frame was flooded because the switch had never seen B. As soon as B replied, the switch knew both locations, and from then on traffic between A and B went only where it needed to.
Ageing and moved devices
MAC table entries expire after a period of silence (300 seconds by default on most switches). This keeps the table small and handles devices that move: when a laptop moves to another port, its next frame updates the entry immediately (rule 1 overwrites it). Here we add time stamps to the model:
class AgingSwitch:
AGE_LIMIT = 300
def __init__(self):
self.table = {} # MAC -> (port, last_seen)
def learn(self, now, port, mac):
old = self.table.get(mac)
self.table[mac] = (port, now)
if old and old[0] != port:
print(f"t={now:>3}: {mac} moved from port {old[0]} to port {port}")
def expire(self, now):
for mac, (port, seen) in list(self.table.items()):
if now - seen > self.AGE_LIMIT:
del self.table[mac]
print(f"t={now:>3}: {mac} aged out (idle {now - seen}s)")
def show(self, now):
entries = ", ".join(f"{m[-2:]}@{p}" for m, (p, _) in sorted(self.table.items()))
print(f"t={now:>3}: table [{entries}]")
sw = AgingSwitch()
sw.learn(0, 1, "mac-01")
sw.learn(10, 2, "mac-02")
sw.learn(20, 3, "mac-03")
sw.show(20)
sw.learn(200, 4, "mac-01") # the laptop was moved to port 4
sw.learn(250, 2, "mac-02")
sw.expire(330) # mac-03 has been silent since t=20
sw.show(330)t= 20: table [01@1, 02@2, 03@3]
t=200: mac-01 moved from port 1 to port 4
t=330: mac-03 aged out (idle 310s)
t=330: table [01@4, 02@2]
Switching loops
Suppose two switches are joined by two cables for redundancy. A broadcast arrives at SW1, which floods it to SW2 over both links. SW2 floods each copy back over the other link, and so on. Ethernet frames have no hop limit (unlike IP's TTL), so the copies circulate forever and multiply: a broadcast storm that saturates the network within seconds. MAC tables also flap as the same source appears on different ports.
# Count broadcast copies circulating between two switches joined by two links.
copies = 1
for round_number in range(1, 7):
copies *= 2 # each switch floods every copy out of both inter-switch links
print(f"after round {round_number}: {copies} copies of one broadcast")after round 1: 2 copies of one broadcast
after round 2: 4 copies of one broadcast
after round 3: 8 copies of one broadcast
after round 4: 16 copies of one broadcast
after round 5: 32 copies of one broadcast
after round 6: 64 copies of one broadcast
The fix is the Spanning Tree Protocol (STP, IEEE 802.1D; modern networks use Rapid STP, 802.1w). Switches elect a root bridge and block just enough ports to leave a loop-free tree. If an active link fails, a blocked port is unblocked within seconds (RSTP) to restore connectivity.
Switch port statistics
On a managed switch you can inspect the MAC table directly. On a Cisco switch:
switch# show mac address-table dynamic
Mac Address Table
-------------------------------------------
Vlan Mac Address Type Ports
---- ----------- -------- -----
10 3c22.fb91.0a7e DYNAMIC Gi1/0/3
10 001a.2b3c.4d5e DYNAMIC Gi1/0/24
20 b827.eb12.3456 DYNAMIC Gi1/0/7
Total Mac Addresses for this criterion: 3Linux bridges (used by Docker and VMs) have the same table: bridge fdb show.
Tip: MAC flooding is a classic attack: an attacker sends thousands of frames with fake source MACs until the table is full, after which the switch floods everything, like a hub, and the attacker can sniff other people's traffic. Port security (limit MACs per port) defends against it.
Test yourself
What does a switch learn from each incoming frame?
- The destination MAC and its port
- The source MAC and the port it arrived on
- The source IP address
- The next router
What does a switch do with a frame whose destination MAC is not in its table?
- Drops it
- Sends it back to the sender
- Floods it out of all ports except the incoming one
- Asks the router
Which protocol prevents switching loops?
- ARP
- STP
- DHCP
- ICMP