← Kỹ sư mạng← Network Engineer
Kỹ sư mạngNetwork Engineer19 Th7, 2026Jul 19, 202622 phút đọc19 min read

Chuyển mạch (Switching)Switching

Thuộc bộ kiến thức Network Engineer Roadmap.

Tổng quan

Switching là tập hợp các cơ chế ở Layer 2 (Data Link) dùng để chuyển các Ethernet frame giữa các host trong cùng một mạng nội bộ một cách nhanh và thông minh nhất có thể. Nếu routing (xem ./07-routing.md) lo việc đưa packet đi giữa các mạng dựa trên IP address, thì switching lo việc chuyển frame trong một mạng dựa trên MAC address. Đây là “cỗ máy chủ lực” của mọi LAN, data center và campus network — nơi phần lớn packet thực sự dành thời gian di chuyển.

Một switch hiện đại làm nhiều hơn việc sao chép bit một cách mù quáng. Nó học vị trí của từng host (MAC address table), chỉ chuyển frame ra đúng port cần thiết (unicast filtering), chia một thiết bị vật lý thành nhiều mạng logic tách biệt (VLAN), ngăn sự cố tự gây ra do loop cáp (Spanning Tree Protocol), gộp nhiều link vật lý thành một đường ống logic để tăng băng thông và dự phòng (EtherChannel/LACP), và — trong data center — kéo dài các đoạn Layer 2 qua một fabric đã routed để virtual machine có thể di chuyển bất cứ đâu (VXLAN).

Note này xây dựng các khái niệm đó từ gốc, kèm cấu hình Cisco IOS thật để bạn gõ vào lab. Các chủ đề liên kết chặt với nhau:

Kiến thức nền tảng

Layer 2 switching thực sự làm gì

Một Ethernet switch là một multi-port bridge. Mỗi port là một collision domain riêng (với full-duplex, collision gần như biến mất), và mặc định tất cả port chia sẻ một broadcast domain duy nhất — cho đến khi bạn tách chúng bằng VLAN. Switch ra quyết định forwarding dựa trên MAC (Media Access Control) address 48-bit trong Ethernet frame header, hoàn toàn không nhìn vào IP payload bên trong.

MAC address viết dưới dạng sáu octet hex, ví dụ 00:1A:2B:3C:4D:5E. Ba octet đầu là OUI (Organizationally Unique Identifier) cấp cho nhà sản xuất; ba octet sau do nhà sản xuất gán cho từng NIC. Broadcast MAC là FF:FF:FF:FF:FF:FF.

Vì sao switch thay thế hub

Một hub là repeater ở Layer 1: nó sao chép mọi bit đến ra tất cả các port khác. Điều đó biến toàn bộ hub thành một collision domain khổng lồ chạy half-duplex CSMA/CD. Càng thêm host, collision càng tăng, throughput thực tế sụp đổ, và mọi host đều thấy traffic của nhau (vấn đề bảo mật và quyền riêng tư).

Một switch khắc phục tất cả:

Đặc tínhHub (Layer 1)Switch (Layer 2)
ForwardingLặp bit ra mọi portChuyển frame theo MAC address
Collision domainMột, dùng chung mọi portMột cho mỗi port
DuplexChỉ half-duplexFull-duplex mỗi port
Băng thôngChia sẻ giữa mọi hostRiêng cho từng port
Bảo mậtAi cũng thấy mọi thứUnicast chỉ tới đúng port đích
SegmentationKhôngVLAN

Vì một switched, full-duplex port tới một host duy nhất không có tranh chấp, CSMA/CD trở nên vô nghĩa và throughput mang tính xác định. Hub đã lỗi thời; ngày nay bạn sẽ không bao giờ triển khai hub nữa.

Ba hành động forwarding: learn, forward/flood, filter

Mỗi frame switch nhận được kích hoạt một tiến trình cốt lõi và một quyết định forwarding.

  1. Learning (học). Switch đọc source MAC của frame và ghi lại {source MAC → port đến → VLAN} vào MAC address table (còn gọi là CAM table). Đây là cách switch khám phá vị trí từng host. Learning diễn ra trên mọi frame.
  2. Quyết định forwarding dựa trên destination MAC:
    • Forward (filter) — nếu destination MAC đã biết và ánh xạ tới một port khác, gửi frame ra đúng port đó. Nếu nó ánh xạ tới cùng port frame vừa đến, filter (loại bỏ) — đích đã nằm trên đoạn mạng đó.
    • Flood — nếu destination MAC chưa biết (chưa có trong table), hoặc là broadcast (FF:FF:...) hay multicast, gửi frame ra tất cả port trong VLAN đó trừ port nó đến. Đây gọi là “unknown-unicast flooding”. Frame phản hồi sẽ dạy cho switch, nên các frame sau đó là unicast.

Chu trình learn/flood/filter chính là toàn bộ bản chất của transparent bridging (IEEE 802.1D). Nó “transparent” vì các host không hề biết switch tồn tại.

Store-and-forward vs cut-through

Khái niệm chính

VLAN (Virtual LAN) — IEEE 802.1Q

Một VLAN là một broadcast domain logic được tạo bằng phần mềm trên switch. Các port gán vào VLAN 10 hoạt động như thể chúng được cắm vào một switch vật lý riêng so với các port ở VLAN 20 — broadcast, unknown unicast và multicast đều nằm trong VLAN. Để chuyển traffic giữa các VLAN bạn phải route (Layer 3).

Lợi ích: segmentation (giới hạn phạm vi ảnh hưởng của broadcast), bảo mật (cô lập các phòng ban/vai trò), linh hoạt (nhóm người dùng theo logic bất kể vị trí vật lý) và tách QoS/voice.

Access port vs trunk port

Tagging 802.1Q và native VLAN

IEEE 802.1Q chèn một tag 4 byte vào Ethernet frame, nằm giữa source MAC và EtherType. Trường quan trọng nhất là VID (VLAN ID), giá trị 12-bit (1–4094; 0 và 4095 được dành riêng). Tag còn mang PCP (Priority Code Point) 3-bit cho 802.1p CoS.

| Dest MAC | Src MAC | 802.1Q Tag (4 byte) | EtherType | Payload | FCS |
                       ├─ TPID 0x8100 (16b)
                       ├─ PCP (3b) | DEI (1b) | VID (12b)

Native VLAN là VLAN duy nhất mà frame của nó đi qua trunk ở dạng untagged (mặc định VLAN 1). Nếu một frame đến trunk mà không có tag, nó được coi là thuộc native VLAN. Native VLAN phải khớp ở cả hai đầu của trunk, nếu không sẽ có VLAN mismatch (CDP sẽ cảnh báo). Best practice bảo mật: đổi native VLAN khỏi VLAN 1 sang một VLAN không dùng và không bao giờ đặt traffic người dùng lên nó — điều này giảm thiểu tấn công VLAN-hopping (double-tagging).

Tạo VLAN và access port:

Switch# configure terminal
Switch(config)# vlan 10
Switch(config-vlan)#  name ENGINEERING
Switch(config-vlan)# exit
Switch(config)# vlan 20
Switch(config-vlan)#  name SALES
Switch(config-vlan)# exit

! Gán access port
Switch(config)# interface range gigabitEthernet 0/1 - 12
Switch(config-if-range)#  switchport mode access
Switch(config-if-range)#  switchport access vlan 10
Switch(config-if-range)# exit

Switch(config)# interface range gigabitEthernet 0/13 - 24
Switch(config-if-range)#  switchport mode access
Switch(config-if-range)#  switchport access vlan 20

Cấu hình trunk 802.1Q:

Switch(config)# interface gigabitEthernet 0/48
Switch(config-if)#  switchport trunk encapsulation dot1q   ! chỉ cần trên switch còn hỗ trợ ISL
Switch(config-if)#  switchport mode trunk
Switch(config-if)#  switchport trunk native vlan 999       ! dời native VLAN khỏi 1
Switch(config-if)#  switchport trunk allowed vlan 10,20,999 ! cắt bỏ tất cả VLAN khác
Switch(config-if)# end

Switch# show interfaces trunk
Switch# show vlan brief

Lưu ý về DTP: Dynamic Trunking Protocol của Cisco có thể tự thương lượng trunk (switchport mode dynamic auto|desirable). Vì lý do bảo mật và tính xác định, hãy cố định mode (access hoặc trunk) và tắt thương lượng bằng switchport nonegotiate trên trunk.

Inter-VLAN routing

VLAN bị cô lập ở Layer 2, nên một router hoặc Layer 3 switch phải chuyển traffic giữa chúng.

Cách A — Router-on-a-stick (ROAS). Một link router vật lý chạy như trunk 802.1Q với một subinterface cho mỗi VLAN, mỗi subinterface đóng vai default gateway của VLAN đó.

Router(config)# interface gigabitEthernet 0/0
Router(config-if)#  no shutdown
Router(config-if)# exit
Router(config)# interface gigabitEthernet 0/0.10
Router(config-subif)#  encapsulation dot1q 10
Router(config-subif)#  ip address 192.168.10.1 255.255.255.0
Router(config-subif)# exit
Router(config)# interface gigabitEthernet 0/0.20
Router(config-subif)#  encapsulation dot1q 20
Router(config-subif)#  ip address 192.168.20.1 255.255.255.0

Đơn giản và rẻ, nhưng link đơn là điểm nghẽn băng thông và điểm lỗi đơn (single point of failure). Phù hợp cho site nhỏ.

Cách B — SVI trên Layer 3 (multilayer) switch. Một SVI (Switched Virtual Interface) là interface routed ảo cho một VLAN, nằm ngay trong engine routing của switch — không cần router ngoài, route ở tốc độ wire trong ASIC. Đây là chuẩn cho lớp distribution của campus/data-center.

L3Switch(config)# ip routing                  ! bật forwarding Layer 3
L3Switch(config)# interface vlan 10
L3Switch(config-if)#  ip address 192.168.10.1 255.255.255.0
L3Switch(config-if)#  no shutdown
L3Switch(config-if)# exit
L3Switch(config)# interface vlan 20
L3Switch(config-if)#  ip address 192.168.20.1 255.255.255.0
L3Switch(config-if)#  no shutdown

Bạn cũng có thể biến một switch port vật lý thành routed port thuần (không switched) bằng no switchport và gán IP trực tiếp — hữu ích cho uplink L3 switch-to-router hoặc switch-to-switch. Xem ./07-routing.md để biết quyết định routing sau đó được thực hiện thế nào.

Voice VLAN

IP phone thường có một switch 3-port tích hợp: uplink tới switch mạng, một port tới PC, và bản thân điện thoại. Tính năng voice VLAN cho phép một access port duy nhất mang đồng thời cả data của PC (untagged, trong access/data VLAN) traffic điện thoại (tagged, trong voice VLAN), nên voice có broadcast domain và QoS riêng.

Switch(config)# interface gigabitEthernet 0/5
Switch(config-if)#  switchport mode access
Switch(config-if)#  switchport access vlan 10      ! data VLAN cho PC
Switch(config-if)#  switchport voice vlan 110      ! voice VLAN (tagged) cho điện thoại
Switch(config-if)#  mls qos trust cos              ! tin tưởng CoS marking từ điện thoại

Spanning Tree Protocol (STP) — IEEE 802.1D / 802.1w

Các link dự phòng giữa các switch là thiết yếu cho tính sẵn sàng — nhưng Ethernet không có trường TTL. Một loop vật lý duy nhất sẽ khiến broadcast frame quay vòng mãi mãi, mỗi switch flood chúng ra mọi port, nhân đôi traffic sau mỗi vòng. Trong vài giây, một broadcast storm làm bão hòa mọi link, MAC table dao động điên loạn khi cùng một source MAC xuất hiện trên nhiều port, và cả LAN sụp đổ. STP tồn tại để bạn có topology vật lý dự phòng mà vẫn đảm bảo topology logic không loop.

STP (802.1D) xây một cây không loop bằng cách bầu một root bridge rồi block mọi đường dự phòng, để lại đúng một đường active tới root từ mỗi switch.

Bầu root bridge và BPDU

Các switch trao đổi BPDU (Bridge Protocol Data Unit) — frame multicast tới 01:80:C2:00:00:00 — để xây cây. Mỗi switch có một Bridge ID (BID) = Bridge Priority (2 byte, mặc định 32768) + MAC address. Trong PVST+, priority còn nhúng VLAN ID (phần “extended system ID”), nên giá trị priority tăng theo bước 4096.

Path cost mặc định IEEE 802.1D-2004 (long/short):

Tốc độ linkCost short-modeCost long-mode
10 Mbps1002,000,000
100 Mbps19200,000
1 Gbps420,000
10 Gbps22,000
100 Gbps200

Port role và port state

Role:

State (802.1D cổ điển): Blocking → Listening → Learning → Forwarding, với max-age 20 s và hai timer forward-delay 15 s, nên hội tụ sau một thay đổi topology mất ~30–50 giây. Sự chậm chạp đó chính là lý do RSTP ra đời.

RSTP (802.1w) và PVST+

! Dùng biến thể rapid, per-VLAN ở mọi nơi
Switch(config)# spanning-tree mode rapid-pvst

! Đặt root một cách xác định cho từng VLAN (load-balancing)
Switch(config)# spanning-tree vlan 10 root primary       ! đặt priority = 24576
Switch(config)# spanning-tree vlan 20 root secondary     ! đặt priority = 28672
! (dạng tường minh tương đương: spanning-tree vlan 10 priority 24576)

Switch# show spanning-tree vlan 10
Switch# show spanning-tree root

Các cơ chế bảo vệ STP (làm cứng biên)

Tính năngÁp dụng trênChức năngLệnh
PortFastAccess/edge portBỏ qua listening/learning, chuyển thẳng sang forwarding cho host đầu cuốispanning-tree portfast
BPDU GuardPortFast/edge portErr-disable port nếu nó nhận BPDU (có người cắm switch vào)spanning-tree bpduguard enable
BPDU FilterEdge portNgăn gửi/nhận BPDU (dùng cẩn thận)spanning-tree bpdufilter enable
Root GuardDesignated port hướng xuống switch downstreamNgăn switch downstream trở thành root (chặn BPDU tốt hơn)spanning-tree guard root
Loop GuardNon-designated portNgăn một blocking port chuyển nhầm sang forwarding nếu BPDU ngừng đếnspanning-tree guard loop
! Best practice: bật PortFast + BPDU Guard cho mọi access port cùng lúc
Switch(config)# spanning-tree portfast default
Switch(config)# spanning-tree portfast bpduguard default

! Theo từng port (host/edge port)
Switch(config)# interface gigabitEthernet 0/1
Switch(config-if)#  spanning-tree portfast
Switch(config-if)#  spanning-tree bpduguard enable

! Bảo vệ hướng xuống switch downstream không bao giờ được làm root
Switch(config)# interface gigabitEthernet 0/48
Switch(config-if)#  spanning-tree guard root

! Tự phục hồi port err-disabled sau 5 phút
Switch(config)# errdisable recovery cause bpduguard
Switch(config)# errdisable recovery interval 300

MAC address table: aging và bảo mật

MAC (CAM) table có kích thước hữu hạn (từ hàng nghìn tới hàng trăm nghìn entry). Entry bị xóa sau một aging timer (mặc định 300 s / 5 phút trên Cisco) không có traffic từ MAC đó, nên table luôn cập nhật khi host di chuyển.

Switch# show mac address-table
Switch# show mac address-table dynamic vlan 10
Switch(config)# mac address-table aging-time 300
Switch(config)# mac address-table static 0000.1111.2222 vlan 10 interface gi0/5

Tấn công MAC flooding và port security

Một tấn công MAC flooding (ví dụ bằng macof) gửi ồ ạt các frame có source MAC giả ngẫu nhiên. CAM table bị lấp đầy; khi đầy, switch không còn học được MAC hợp lệ và flood mọi frame unknown-unicast ra tất cả các port — biến switch thành hub để kẻ tấn công có thể sniff traffic của mọi người (CAM overflow / fail-open).

Port security là biện pháp đối phó: giới hạn số MAC một port được học, và chọn điều gì xảy ra khi vi phạm.

Switch(config)# interface gigabitEthernet 0/5
Switch(config-if)#  switchport mode access
Switch(config-if)#  switchport port-security
Switch(config-if)#  switchport port-security maximum 2
Switch(config-if)#  switchport port-security mac-address sticky   ! học & lưu MAC hiện tại
Switch(config-if)#  switchport port-security violation restrict   ! shutdown | restrict | protect
Switch(config-if)# end

Switch# show port-security
Switch# show port-security address

Các mode vi phạm: protect (âm thầm loại bỏ MAC thừa), restrict (loại bỏ + log/SNMP + đếm), shutdown (err-disable port — mặc định và an toàn nhất).

Link aggregation gộp 2–8 link vật lý song song thành một link logic (một EtherChannel / Port-Channel) cho hai lợi ích: nhiều băng thông hơn (throughput tổng hợp) và dự phòng (nếu một member hỏng, traffic chuyển sang các member còn lại mà không cần STP hội tụ lại — STP thấy bundle là một link nên không member nào bị block). Traffic được trải trên các member bằng thuật toán hashing (theo src/dst MAC, IP hoặc L4 port) nên một flow đơn luôn nằm trên một member (tránh reorder).

Các giao thức thương lượng:

Cả hai đầu phải khớp về speed, duplex, allowed VLAN, và trunk/access mode, nếu không bundle sẽ không hình thành.

! EtherChannel LACP dạng Layer 2 trunk trên hai link
Switch(config)# interface range gigabitEthernet 0/1 - 2
Switch(config-if-range)#  switchport mode trunk
Switch(config-if-range)#  switchport trunk allowed vlan 10,20
Switch(config-if-range)#  channel-group 1 mode active         ! LACP active
Switch(config-if-range)# exit

! Cấu hình interface Port-Channel logic một lần; các member kế thừa
Switch(config)# interface port-channel 1
Switch(config-if)#  switchport mode trunk
Switch(config-if)#  switchport trunk allowed vlan 10,20
Switch(config-if)# exit

! Tinh chỉnh hash load-balancing (global)
Switch(config)# port-channel load-balance src-dst-ip

Switch# show etherchannel summary
Switch# show lacp neighbor

Một EtherChannel Layer 3 (uplink đã routed) thêm no switchport + IP trên Port-Channel:

Switch(config)# interface port-channel 2
Switch(config-if)#  no switchport
Switch(config-if)#  ip address 10.0.0.1 255.255.255.252

MLAG / vPC / StackWise: Các nhà cung cấp cho phép một Port-Channel trải trên hai switch vật lý (Cisco vPC trên Nexus, StackWise/VSS trên Catalyst; MLAG nói chung) để một thiết bị downstream dual-home tới hai chassis với một bundle logic — dự phòng switch trọn vẹn mà không có link nào bị block. Xem ./09-redundancy-and-high-availability.md.

VXLAN — Layer 2 overlay trên Layer 3

VLAN cổ điển có trần cứng 4094 ID (trường 802.1Q 12-bit) và không thể kéo dài một broadcast domain qua một core đã routed — một vấn đề thực sự với cloud multi-tenant và với việc di chuyển VM sống giữa các pod của data center.

VXLAN (Virtual Extensible LAN, RFC 7348) giải quyết cả hai. Đây là một overlay MAC-in-UDP: một Ethernet frame gốc được đóng gói bên trong một UDP packet (dest port 4789) và route qua bất kỳ underlay IP (Layer 3) nào. Các thuật ngữ chính:

Kết quả: hai host bất kỳ trong cùng một VNI trông như nằm trên cùng một đoạn L2 dù packet được route giữa các rack và pod qua một fabric Layer 3 spine-leaf có khả năng mở rộng, không loop, và load-balance bằng ECMP. Control-plane học MAC/IP thường dùng BGP EVPN thay vì flood-and-learn. VXLAN là nền tảng của mạng data-center và cloud hiện đại; được trình bày sâu trong ./16-cloud-networking.md.

Bảng tóm tắt các công nghệ Layer 2 chính

Công nghệChuẩnLayerVấn đề giải quyếtThành phần chính
Transparent bridgingIEEE 802.1DL2Chuyển frame mà host không hay biếtMAC address table
VLAN taggingIEEE 802.1QL2Chia một switch thành nhiều broadcast domainTag 4 byte, VID 12-bit
STPIEEE 802.1DL2Ngăn loop trên link dự phòngBPDU, root bridge
RSTPIEEE 802.1wL2Hội tụ không loop nhanh (<1 s)Proposal/agreement
PVST+ / Rapid-PVST+CiscoL2STP per-VLAN + load balancingMột instance mỗi VLAN
MSTIEEE 802.1sL2Ánh xạ nhiều VLAN vào ít instance STPMST instance/region
Link aggregationIEEE 802.3ad (LACP)L2/L3Băng thông + dự phòng linkPort-Channel / bundle
Port securityCiscoL2Chặn MAC flooding / host giả mạoMax MAC + hành động vi phạm
Inter-VLAN routingL3Chuyển traffic giữa các VLANSubinterface / SVI
VXLANRFC 7348L2 trên L3Kéo dài L2 qua fabric routed, 16M segmentVNI, VTEP, UDP/4789

Best Practices

Tài liệu tham khảo

Part of the Network Engineer Roadmap knowledge base.

Overview

Switching is the set of Layer 2 (Data Link) mechanisms that move Ethernet frames between hosts on the same local network as fast and as intelligently as possible. If routing (see ./07-routing.md) is about getting packets between networks based on IP addresses, switching is about getting frames within a network based on MAC addresses. It is the workhorse of every LAN, data center, and campus network — the layer where the vast majority of packets actually spend their time.

A modern switch does far more than blindly copy bits. It learns where every host lives (MAC address table), forwards frames only to the port that needs them (unicast filtering), carves one physical box into many isolated logical networks (VLANs), prevents self-inflicted meltdowns from cabling loops (Spanning Tree Protocol), bundles multiple physical links into one logical pipe for bandwidth and redundancy (EtherChannel/LACP), and — in the data center — stretches Layer 2 segments across a routed fabric so that virtual machines can move anywhere (VXLAN).

This note builds those ideas from the ground up with real Cisco IOS configuration you can type into a lab. The topics interlock:

Fundamentals

What Layer 2 switching actually does

An Ethernet switch is a multi-port bridge. Each port is its own collision domain (with full-duplex, collisions effectively disappear), and by default all ports share one broadcast domain — until you split them with VLANs. A switch makes forwarding decisions based on the 48-bit MAC (Media Access Control) address in the Ethernet frame header, never looking at the IP payload inside.

A MAC address is written as six hex octets, e.g. 00:1A:2B:3C:4D:5E. The first three octets are the OUI (Organizationally Unique Identifier) assigned to the vendor; the last three are assigned by the vendor to the individual NIC. The broadcast MAC is FF:FF:FF:FF:FF:FF.

Why switches replaced hubs

A hub is a Layer 1 repeater: it copies every incoming bit out of every other port. That makes the whole hub one giant collision domain running half-duplex CSMA/CD. As you add hosts, collisions rise, effective throughput collapses, and every host sees every other host’s traffic (a security and privacy problem).

A switch fixes all of this:

PropertyHub (Layer 1)Switch (Layer 2)
ForwardingRepeats bits to all portsForwards frames by MAC address
Collision domainOne shared for all portsOne per port
DuplexHalf-duplex onlyFull-duplex per port
BandwidthShared among all hostsDedicated per port
SecurityEveryone sees everythingUnicast reaches only the target port
SegmentationNoneVLANs

Because a switched, full-duplex port to a single host has no contention, CSMA/CD becomes irrelevant and throughput is deterministic. Hubs are obsolete; you will never deploy one today.

The three forwarding actions: learn, forward/flood, filter

Every frame a switch receives triggers one core process and one forwarding decision.

  1. Learning. The switch reads the frame’s source MAC and records {source MAC → ingress port → VLAN} in its MAC address table (also called the CAM table). This is how the switch discovers where each host lives. Learning happens on every frame.
  2. Forwarding decision based on the destination MAC:
    • Forward (filter) — if the destination MAC is known and maps to a different port, send the frame out that one port only. If it maps to the same port the frame arrived on, filter (drop) it — the destination is already on that segment.
    • Flood — if the destination MAC is unknown (not yet in the table), or is a broadcast (FF:FF:...) or multicast, send the frame out all ports in that VLAN except the one it came in on. This is “unknown-unicast flooding.” The reply then teaches the switch, so subsequent frames are unicast.

This learn/flood/filter cycle is the entire essence of transparent bridging (IEEE 802.1D). It is “transparent” because hosts have no idea a switch exists.

Store-and-forward vs cut-through

Key Concepts

VLANs (Virtual LANs) — IEEE 802.1Q

A VLAN is a logical broadcast domain created in software on a switch. Ports assigned to VLAN 10 behave as if they were plugged into a separate physical switch from ports in VLAN 20 — broadcasts, unknown unicast, and multicast stay inside the VLAN. To move traffic between VLANs you must route (Layer 3).

Benefits: segmentation (limit broadcast blast radius), security (isolate departments/roles), flexibility (group users logically regardless of physical location), and QoS/voice separation.

Access ports vs trunk ports

802.1Q tagging and the native VLAN

IEEE 802.1Q inserts a 4-byte tag into the Ethernet frame between the source MAC and the EtherType. The key field is the VID (VLAN ID), a 12-bit value (1–4094; 0 and 4095 reserved). The tag also carries a 3-bit PCP (Priority Code Point) for 802.1p CoS.

| Dest MAC | Src MAC | 802.1Q Tag (4 bytes) | EtherType | Payload | FCS |
                        ├─ TPID 0x8100 (16b)
                        ├─ PCP (3b) | DEI (1b) | VID (12b)

The native VLAN is the one VLAN whose frames traverse a trunk untagged (default VLAN 1). If a frame arrives on a trunk without a tag, it is assumed to belong to the native VLAN. The native VLAN must match on both ends of a trunk or you get a VLAN mismatch (CDP will warn you). Security best practice: change the native VLAN away from 1 to an unused VLAN and never put user traffic on it — this mitigates VLAN-hopping (double-tagging) attacks.

Creating VLANs and access ports:

Switch# configure terminal
Switch(config)# vlan 10
Switch(config-vlan)#  name ENGINEERING
Switch(config-vlan)# exit
Switch(config)# vlan 20
Switch(config-vlan)#  name SALES
Switch(config-vlan)# exit

! Assign access ports
Switch(config)# interface range gigabitEthernet 0/1 - 12
Switch(config-if-range)#  switchport mode access
Switch(config-if-range)#  switchport access vlan 10
Switch(config-if-range)# exit

Switch(config)# interface range gigabitEthernet 0/13 - 24
Switch(config-if-range)#  switchport mode access
Switch(config-if-range)#  switchport access vlan 20

Configuring an 802.1Q trunk:

Switch(config)# interface gigabitEthernet 0/48
Switch(config-if)#  switchport trunk encapsulation dot1q   ! needed only on switches that also support ISL
Switch(config-if)#  switchport mode trunk
Switch(config-if)#  switchport trunk native vlan 999       ! move native VLAN off 1
Switch(config-if)#  switchport trunk allowed vlan 10,20,999 ! prune everything else
Switch(config-if)# end

Switch# show interfaces trunk
Switch# show vlan brief

DTP note: Cisco’s Dynamic Trunking Protocol can auto-negotiate trunks (switchport mode dynamic auto|desirable). For security and predictability, hard-code the mode (access or trunk) and disable negotiation with switchport nonegotiate on trunks.

Inter-VLAN routing

VLANs are isolated at Layer 2, so a router or Layer 3 switch must move traffic between them.

Option A — Router-on-a-stick (ROAS). One physical router link runs as an 802.1Q trunk with a subinterface per VLAN, each acting as that VLAN’s default gateway.

Router(config)# interface gigabitEthernet 0/0
Router(config-if)#  no shutdown
Router(config-if)# exit
Router(config)# interface gigabitEthernet 0/0.10
Router(config-subif)#  encapsulation dot1q 10
Router(config-subif)#  ip address 192.168.10.1 255.255.255.0
Router(config-subif)# exit
Router(config)# interface gigabitEthernet 0/0.20
Router(config-subif)#  encapsulation dot1q 20
Router(config-subif)#  ip address 192.168.20.1 255.255.255.0

Simple and cheap, but the single link is a bandwidth bottleneck and single point of failure. Fine for small sites.

Option B — SVI on a Layer 3 (multilayer) switch. A Switched Virtual Interface (SVI) is a virtual routed interface for a VLAN, living inside the switch’s own routing engine — no external router, wire-speed routing in ASICs. This is the standard for campus/data-center distribution layers.

L3Switch(config)# ip routing                  ! enable Layer 3 forwarding
L3Switch(config)# interface vlan 10
L3Switch(config-if)#  ip address 192.168.10.1 255.255.255.0
L3Switch(config-if)#  no shutdown
L3Switch(config-if)# exit
L3Switch(config)# interface vlan 20
L3Switch(config-if)#  ip address 192.168.20.1 255.255.255.0
L3Switch(config-if)#  no shutdown

You can also turn a physical switch port into a pure routed (non-switched) port with no switchport and give it an IP directly — useful for switch-to-router or switch-to-switch L3 uplinks. See ./07-routing.md for how routing decisions are then made.

Voice VLAN

IP phones typically have a built-in 3-port switch: uplink to the network switch, a port to the PC, and the phone itself. The voice VLAN feature lets a single access port carry PC data (untagged, in the access/data VLAN) and phone traffic (tagged, in the voice VLAN) simultaneously, so voice gets its own broadcast domain and QoS.

Switch(config)# interface gigabitEthernet 0/5
Switch(config-if)#  switchport mode access
Switch(config-if)#  switchport access vlan 10      ! data VLAN for the PC
Switch(config-if)#  switchport voice vlan 110      ! tagged voice VLAN for the phone
Switch(config-if)#  mls qos trust cos              ! trust CoS marking from the phone

Spanning Tree Protocol (STP) — IEEE 802.1D / 802.1w

Redundant links between switches are essential for availability — but Ethernet has no TTL field. A single physical loop will circulate broadcast frames forever, each switch flooding them out every port, doubling the traffic on every pass. Within seconds a broadcast storm saturates every link, MAC tables thrash as the same source MAC appears on multiple ports, and the whole LAN melts down. STP exists to give you redundant physical topology while guaranteeing a loop-free logical topology.

STP (802.1D) builds a loop-free tree by electing one root bridge and then blocking every redundant path, leaving exactly one active path to the root from every switch.

Root bridge election and BPDUs

Switches exchange BPDUs (Bridge Protocol Data Units) — multicast frames to 01:80:C2:00:00:00 — to build the tree. Each switch has a Bridge ID (BID) = Bridge Priority (2 bytes, default 32768) + MAC address. In PVST+, the priority also embeds the VLAN ID (the “extended system ID”), so priority values increment in steps of 4096.

Default IEEE 802.1D-2004 (long/short) path costs:

Link speedShort-mode costLong-mode cost
10 Mbps1002,000,000
100 Mbps19200,000
1 Gbps420,000
10 Gbps22,000
100 Gbps200

Port roles and states

Roles:

States (classic 802.1D): Blocking → Listening → Learning → Forwarding, with a 20 s max-age and two 15 s forward-delay timers, so converging after a topology change takes ~30–50 seconds. That slowness is why RSTP exists.

RSTP (802.1w) and PVST+

! Use the rapid, per-VLAN variant everywhere
Switch(config)# spanning-tree mode rapid-pvst

! Deterministically set the root for each VLAN (load-balancing)
Switch(config)# spanning-tree vlan 10 root primary       ! sets priority to 24576
Switch(config)# spanning-tree vlan 20 root secondary     ! sets priority to 28672
! (equivalent explicit form: spanning-tree vlan 10 priority 24576)

Switch# show spanning-tree vlan 10
Switch# show spanning-tree root

STP protections (edge hardening)

FeatureApplied onWhat it doesCommand
PortFastAccess/edge portsSkips listening/learning, goes straight to forwarding for end hostsspanning-tree portfast
BPDU GuardPortFast/edge portsErr-disables a port if it receives a BPDU (someone plugged in a switch)spanning-tree bpduguard enable
BPDU FilterEdge portsSuppresses sending/receiving BPDUs (use with care)spanning-tree bpdufilter enable
Root GuardDesignated ports toward downstream switchesPrevents a downstream switch from becoming root (blocks superior BPDUs)spanning-tree guard root
Loop GuardNon-designated portsPrevents a blocking port from wrongly becoming forwarding if BPDUs stopspanning-tree guard loop
! Best practice: enable PortFast + BPDU Guard on all access ports at once
Switch(config)# spanning-tree portfast default
Switch(config)# spanning-tree portfast bpduguard default

! Per-port (host/edge port)
Switch(config)# interface gigabitEthernet 0/1
Switch(config-if)#  spanning-tree portfast
Switch(config-if)#  spanning-tree bpduguard enable

! Protect toward a downstream switch that must never be root
Switch(config)# interface gigabitEthernet 0/48
Switch(config-if)#  spanning-tree guard root

! Recover err-disabled ports automatically after 5 minutes
Switch(config)# errdisable recovery cause bpduguard
Switch(config)# errdisable recovery interval 300

MAC address table: aging, and security

The MAC (CAM) table is finite (thousands to hundreds of thousands of entries). Entries are removed after an aging timer (default 300 s / 5 minutes on Cisco) of no traffic from that MAC, so the table stays current as hosts move.

Switch# show mac address-table
Switch# show mac address-table dynamic vlan 10
Switch(config)# mac address-table aging-time 300
Switch(config)# mac address-table static 0000.1111.2222 vlan 10 interface gi0/5

MAC flooding attack and port security

A MAC flooding attack (e.g. via macof) sends a torrent of frames with random bogus source MACs. The CAM table fills up; when full, the switch can no longer learn legitimate MACs and floods all unknown-unicast frames out every port — effectively turning the switch into a hub so the attacker can sniff everyone’s traffic (CAM overflow / fail-open).

Port security is the countermeasure: cap how many MACs a port may learn, and choose what happens on violation.

Switch(config)# interface gigabitEthernet 0/5
Switch(config-if)#  switchport mode access
Switch(config-if)#  switchport port-security
Switch(config-if)#  switchport port-security maximum 2
Switch(config-if)#  switchport port-security mac-address sticky   ! learn & save current MACs
Switch(config-if)#  switchport port-security violation restrict   ! shutdown | restrict | protect
Switch(config-if)# end

Switch# show port-security
Switch# show port-security address

Violation modes: protect (silently drop extra MACs), restrict (drop + log/SNMP + counter), shutdown (err-disable the port — the default and most secure).

Link aggregation bundles 2–8 parallel physical links into one logical link (an EtherChannel / Port-Channel) for two wins: more bandwidth (aggregate throughput) and redundancy (if one member fails, traffic shifts to the survivors with no STP reconvergence — STP sees the bundle as one link, so no member is blocked). Traffic is spread across members by a hashing algorithm (on src/dst MAC, IP, or L4 port) so any single flow stays on one member (avoids reordering).

Negotiation protocols:

Both ends must agree on speed, duplex, allowed VLANs, and trunk/access mode, or the bundle won’t form.

! LACP Layer 2 trunk EtherChannel across two links
Switch(config)# interface range gigabitEthernet 0/1 - 2
Switch(config-if-range)#  switchport mode trunk
Switch(config-if-range)#  switchport trunk allowed vlan 10,20
Switch(config-if-range)#  channel-group 1 mode active         ! LACP active
Switch(config-if-range)# exit

! Configure the logical Port-Channel interface once; members inherit it
Switch(config)# interface port-channel 1
Switch(config-if)#  switchport mode trunk
Switch(config-if)#  switchport trunk allowed vlan 10,20
Switch(config-if)# exit

! Tune the load-balancing hash (global)
Switch(config)# port-channel load-balance src-dst-ip

Switch# show etherchannel summary
Switch# show lacp neighbor

A Layer 3 EtherChannel (routed uplink) adds no switchport + an IP on the Port-Channel:

Switch(config)# interface port-channel 2
Switch(config-if)#  no switchport
Switch(config-if)#  ip address 10.0.0.1 255.255.255.252

MLAG / vPC / StackWise: Vendors let a Port-Channel span two physical switches (Cisco vPC on Nexus, StackWise/VSS on Catalyst; MLAG generically) so a downstream device dual-homes to two chassis with one logical bundle — full switch redundancy with no blocked links. See ./09-redundancy-and-high-availability.md.

VXLAN — Layer 2 overlay over Layer 3

Classic VLANs have a hard ceiling of 4094 IDs (the 12-bit 802.1Q field) and cannot stretch a broadcast domain across a routed core — a real problem for multi-tenant clouds and for live VM migration across data-center pods.

VXLAN (Virtual Extensible LAN, RFC 7348) solves both. It is a MAC-in-UDP overlay: an original Ethernet frame is encapsulated inside a UDP packet (dest port 4789) and routed across any IP (Layer 3) underlay. Key terms:

The payoff: any two hosts in the same VNI appear to be on the same L2 segment even though the packets are routed between racks and pods over a scalable, loop-free, ECMP-load-balanced Layer 3 spine-leaf fabric. Control-plane MAC/IP learning is typically done with BGP EVPN rather than flood-and-learn. VXLAN is the foundation of modern data-center and cloud networking; it is covered in depth in ./16-cloud-networking.md.

Summary of key Layer 2 technologies

TechnologyStandardLayerProblem it solvesKey artifact
Transparent bridgingIEEE 802.1DL2Forward frames without hosts knowingMAC address table
VLAN taggingIEEE 802.1QL2Segment one switch into many broadcast domains4-byte tag, 12-bit VID
STPIEEE 802.1DL2Prevent loops on redundant linksBPDU, root bridge
RSTPIEEE 802.1wL2Fast (<1 s) loop-free convergenceProposal/agreement
PVST+ / Rapid-PVST+CiscoL2Per-VLAN STP + load balancingOne instance per VLAN
MSTIEEE 802.1sL2Map many VLANs to few STP instancesMST instances/regions
Link aggregationIEEE 802.3ad (LACP)L2/L3Bandwidth + link redundancyPort-Channel / bundle
Port securityCiscoL2Stop MAC flooding / rogue hostsMax MAC + violation action
Inter-VLAN routingL3Move traffic between VLANsSubinterface / SVI
VXLANRFC 7348L2 over L3Stretch L2 across routed fabric, 16M segmentsVNI, VTEP, UDP/4789

Best Practices

References