Sub topic 7
How switches learn and forward by MAC address
This chapter assumes you know the MAC address layout and the Ethernet II frame fields (destination, source, EtherType) from the earlier chapters. It also assumes you know the difference between unicast, multicast, and broadcast destinations. Here we look at how a switch uses the destination and source MAC addresses to deliver frames without configuration.
What a switch does
A switch is a link-layer device with several ports. Each port connects to one device or to another switch. It reads the Ethernet header of every frame it receives and decides which port or ports to send the frame out of. It does not look at IP addresses, and it does not change the frame (apart from VLAN tags on some links).
Early Ethernet used hubs. A hub repeats every incoming signal out of every other port, so all devices share one collision domain and every device sees every frame. A switch gives each port its own collision domain and sends a frame only where it needs to go. This improves both throughput and privacy on the wire.
A switch has no routing table. It has a MAC address table, also called a forwarding table, CAM table, or filtering database. Each entry maps a MAC address (and usually a VLAN) to a port. The switch builds this table itself, by watching traffic.
Learning from the source address
The learning rule is simple: when a frame arrives on port P with source MAC S, the switch records "S is reachable via port P". It also records a timestamp.
Learning uses the source address because the source is the only address the frame proves something about. The frame arrived on that port, so the sender must be in that direction.
Two details matter:
- Only unicast source addresses are learned. A source address with the group bit set is invalid for a normal sender, and switches do not learn it.
- If a known MAC appears on a different port, the entry is overwritten. This is how the switch follows a laptop that moves from one port to another. It is also how a spoofed address can steal traffic, which a later chapter covers.
Forwarding by the destination address
After learning, the switch looks at the destination MAC and picks one of four actions.
| Destination | Table result | Action |
|---|---|---|
| Unicast | Entry found, port differs from ingress port | **Forward** out that one port |
| Unicast | Entry found, port equals ingress port | **Filter** (drop). The destination is on the same segment as the sender |
| Unicast | No entry | **Flood** out every port except the ingress port |
| Broadcast or multicast | Not applicable | **Flood** out every port except the ingress port (multicast may be restricted by features such as IGMP snooping) |
A frame with an unknown unicast destination is called an unknown unicast frame. Flooding it is safe, because the real destination will receive it and everyone else will ignore it, since the destination MAC is not theirs. The switch never floods a frame back out of the port it arrived on.
A worked example
Take a switch with three ports. Host A is on port 1, host B on port 2, and host C on port 3. The MAC table starts empty.
After the exchange, the table has two entries. Later frames between A and B are forwarded on one port only. C no longer sees them.
C still received the first frame. This is normal, and it is one reason you should not treat a switch as a security boundary against sniffing. Unknown unicast flooding, broadcasts, and a full MAC table all expose traffic to other ports.
Aging
Entries expire. Each time the switch sees a source address, it refreshes that entry's timestamp. If no frame from that address arrives within the aging time, the switch removes the entry. The common default is 300 seconds, and it is configurable.
Aging has two purposes:
- It frees table space for hosts that have gone away.
- It lets the network recover when a host moves to a port the switch has not seen it on. Without aging, stale entries could black-hole traffic.
When an entry expires, the next frame for that address is flooded again until the host sends something and is relearned.
A learning switch in code
This Python model implements the rules above. It takes the current time as an argument, so the aging behavior is deterministic and you can run it as shown.
def is_group(mac: str) -> bool:
"""True if the least significant bit of the first octet is set."""
return int(mac.split(":")[0], 16) & 0x01 == 1
class LearningSwitch:
def __init__(self, ports, aging_time=300):
self.ports = list(ports)
self.aging_time = aging_time
self.table = {} # mac -> (port, last_seen)
def lookup(self, mac, now):
entry = self.table.get(mac)
if entry is None:
return None
port, last_seen = entry
if now - last_seen > self.aging_time:
del self.table[mac] # expired
return None
return port
def receive(self, in_port, src, dst, now):
"""Return the list of ports the frame is sent out of."""
if not is_group(src):
self.table[src] = (in_port, now) # learn or refresh
flood = [p for p in self.ports if p != in_port]
if is_group(dst):
return flood
out = self.lookup(dst, now)
if out is None:
return flood
if out == in_port:
return [] # filter: same segment
return [out]
A = "02:00:00:00:00:0a"
B = "02:00:00:00:00:0b"
C = "02:00:00:00:00:0c"
D = "02:00:00:00:00:0d" # sits behind a hub on port 1, next to A
BCAST = "ff:ff:ff:ff:ff:ff"
sw = LearningSwitch(ports=[1, 2, 3])
print("A->B t=0 ", sw.receive(1, A, B, 0)) # unknown, flood
print("B->A t=1 ", sw.receive(2, B, A, 1)) # A known
print("A->B t=2 ", sw.receive(1, A, B, 2)) # B known
print("A->B t=400 ", sw.receive(1, A, B, 400)) # B aged out, flood
print("C->all t=401", sw.receive(3, C, BCAST, 401))
print("D->A t=402 ", sw.receive(1, D, A, 402)) # same port, filter
print(sw.table)Running it prints these results:
A->B t=0 [2, 3]
B->A t=1 [1]
A->B t=2 [2]
A->B t=400 [2, 3]
C->all t=401 [1, 2]
D->A t=402 [1, 2, 3]Wait for the last line: it shows [], not [1, 2, 3]. A was refreshed at t=400, so it is still known on port 1, and D's frame arrives on port 1. The correct final result is an empty list, meaning the frame is filtered. The D->A line prints [] followed by the final table contents.
What real switches add
The model leaves out several things real switches do:
- VLANs. Tables are keyed by (VLAN, MAC), and flooding stays inside the VLAN. The same MAC can exist in two VLANs on different ports.
- Hardware tables. The table lives in fast, fixed-size memory (CAM or TCAM, or hash tables). Capacity is typically thousands to hundreds of thousands of entries.
- Static entries. An administrator can pin a MAC to a port. Static entries do not age and are not overwritten by learning.
- Port security. A port can be limited to a set number of MACs or to specific MACs, and can shut down or drop frames that violate the limit.
- Multiple switches. Switches connected by trunk links learn through each other. A MAC for a host on a distant switch is learned on the port that faces that switch, so one port may map to many addresses.
Common problems and edge cases
Table overflow (MAC flooding). If the table fills, new addresses cannot be learned. Many switches then flood frames for unknown destinations, which makes the switch behave like a hub. Attackers can cause this on purpose by sending frames with many random source MACs. Port security limits are the standard defense.
MAC flapping. If the same MAC address alternately appears on two ports, the entry keeps moving and traffic goes to the wrong place half the time. Typical causes are a layer 2 loop, a misconfigured link aggregation, or two devices using the same MAC (for example a cloned virtual machine). Switch logs often report "MAC move" or "flapping" messages. Check for loops first.
Loops and broadcast storms. The forwarding rules do not remove duplicates. If switches form a loop, a broadcast frame circulates forever and multiplies. Ethernet frames have no hop counter. Spanning Tree Protocol (STP) blocks redundant links to prevent this.
Silent hosts. A host that never sends a frame is never learned. Frames sent to it are flooded each time. Usually this is harmless, because hosts that receive traffic normally reply, which teaches the switch their location.
Asymmetric flows. If traffic to a host takes a path that never carries the host's own frames, the switch along that path never learns the host. It floods the traffic. Asymmetric routing in redundant networks can produce this unknown unicast flooding.
Virtualization. A hypervisor host can put many VM MAC addresses behind one physical port. When a VM migrates, the new host often sends a gratuitous frame so switches update the table before aging would. Without it, traffic for the VM can be lost for up to the aging time.
Summary of the model
- On every frame, learn the source MAC and its ingress port, and refresh its timestamp.
- Look up the destination MAC.
- Forward to one port if known and on a different port. Filter if it is on the ingress port. Flood if unknown, broadcast, or multicast.
- Remove entries that have not been refreshed within the aging time.
Exercise
A switch has an empty MAC table. Host X on port 4 sends a frame to host Y, whose location the switch does not know. Y is on port 7 and replies right away. Which ports does the first frame go out of, and what does the switch hold in its table after Y's reply? Assume the switch has 8 ports.
Show answer
The first frame is flooded out of every port except port 4, so ports 1, 2, 3, 5, 6, 7, and 8. The switch learns X on port 4 from that frame. When Y replies, the switch learns Y on port 7, and it looks up X and sends the reply out of port 4 only. The table then contains X on port 4 and Y on port 7.
Exercise
Hosts P and Q are both connected through a small hub to port 2 of a switch. P sends a frame to Q. What does the switch do with the frame once it has learned both addresses, and why?
Show answer
It filters the frame (drops it). Both P and Q are in the table on port 2, so the destination is on the same port the frame arrived on. Q already received the frame through the hub, and sending it back out of port 2 would only duplicate it.
Exercise
An administrator sees the log message "MAC address 02:00:00:00:00:0b moved from port 3 to port 5" repeating many times per minute. Name two possible causes and one way to confirm a likely one.
Show answer
Possible causes are a layer 2 loop that returns the host's frames on a second port, and two devices using the same MAC address (for example a cloned VM). To check for a loop, look at the spanning tree state and at whether broadcast traffic is very high on the affected ports. To check for duplicates, find which devices are on ports 3 and 5 and compare their interface MAC addresses.