Given a packet, can you tell, if it will get switched or routed ? What algorithm will you use.
To understand this, let us dig into what happens during switching and routing.
Switching happens in the same network. And routing works across the network.
For routing to happen L3 lookup is necessary. The L3 data present in the packet header includes Source Ip, Destination Ip etc.
But when will L3 lookup happen ?
After L2 lookup matches then L3 lookup starts (Similarly, after L3 lookup matches then L4 lookup will start and so on, for the entire network layers)
Switching / L2 Lookup
When the packet arrives on a port, the destination MAC address present as a part of the packet header is matched against the MAC address of the port on which this packet is received.
If the Destination MAC address present in the packet header is same to the MAC address of the port on which this packet is received, the packet has reached its destination when Layer 2 is concerned. The packet can now proceed for L3 lookup.
But what will happen if the packet’s destination MAC does not match with the MAC address of the port on which it is received ?
Then, the MAC address table lookup happens. The MAC address table, is a table that has the following key fields (or columns). Let us take an example
The above tables tells that MAC aa:00:bb:00:cc:00 is learnt on port 1/1/1 and belongs to VLAN 10. Or in other words, to reach destination MAC aa:00:bb:00:cc:00 use port 1/1/1 as the egress port for all packets part of VLAN 10.
As the MAC is learnt so the type is “dynamic”. On the other hand if administrator configures the above table entry manually then the type becomes “static”.
So when MAC table lookup happens, the destination MAC specified in the packet header matches with an entry in the MAC address table, for the same vlan, then the packet is forwarded to that port. In other words, this is switching.
Routing / L3 Lookup
As discussed above, L3 lookup will happen after L2 match is found – that is when the destination MAC of the packet matches with the mac address of the port on which it is received.
Now it can go ahead for L3 lookup and see if the Destination IP present in the packet header also matches with the IP address of the port where the packet is received. (Or it can be a L3 virtual port as well, example a SVI – switch virtual interface, which is essentially is a L3 VLAN port ).
If the above matches, the packet has reached the final destination. If it does not match, then Routing table lookup happens and the packet gets routed to another network. In other words, routing takes place.
So to answer the question “what decides if a packet will get switched or routed” as you can see it all dependents on the Destination MAC.
So if the packet has not yet reached its destination MAC, switching happens. If packet has reached the destination MAC, it checks to see if routing is necessary.