When a packet arrives in the port how does the switch know what is the VLAN tag in that packet. In other words what VLAN does that packet belong ?
In a switch what is received is an ethernet packet. Here is how a typical ethernet untagged frame looks like (excluding the preamble, crc etc)
When a packet is VLAN tagged, that VLAN information is also sent in the above Ethernet Frame.
How does the VLAN fit into the ethernet frame? Vlan is part of the .1Q (Dot1Q) header.
The .1Q header is of 4 bytes. It is represented as
TPID: Tag protocol identifier. When it is set to 0x8100, it represents .1Q vlan tagged packet.
VID: Vlan Identifier, is a 12 bits representation of vlan.
The entire packet frame with the .1Q header looks like
This is as per the IEEE 802.1Q (or Dot1q) standard.
The key here is to note the overlap between the frame structure of a normal untagged ethernet packet without any VLAN information and the VLAN tagged packet (Figure 1 vs Figure 3).
You will notice that the ethertype (in Figure 1) and the VLAN tag information (in Figure 3) resides at the same offset from the start of the packet. That is 12 bytes from the start of the packet.
Now when any packet is received by the switch, part of the switching algorithm is to skip the 6 bytes Destination Mac + 6 bytes of Source Mac (i.e total 12 bytes) and read the next 2 bytes.
If the value is 0x8100, which is the TPID as show in the above diagram, then the switch knows that the VLAN tag is present and parses the frame further to retrieve it.
Question for you :-