A spanning tree is created so that loops do not occur in a network when there are multiple paths to a host that is down. First, using a beautiful ASCII diagram, I will show you some examples where spanning trees are needed:

                     B1              H = Host
                    / \              B = Bridge
                   /   \
              H3--B3   |
                   \   /
                    \ /
                     H2 (down)
Now, picture this: H1 is sending a packet to H2 which at the moment is down for some irrelevant reason. H1 send the packet to B1, which thinks that B2 knows the path to H2. Since H2 is down, B2 does not have access to it, therefore B2 forwards the packet to B3 who might have a path to it. As any other bridge in this network, B3 hasn't got a path to H2 either, therefore the packet is forwarded to B1. B1 will then forward the packet to B2 and so on.

To prevent these types of loops, spanning trees got invented. To create a spanning tree, first a root bridge must be selected. This is how it is done:
  1. Each bridge starts to advertise itself as the root-bridge, sending CBPDUs containing the MAC Adress of itself, and the cost of the interface the CBPDU was sent from.

    The cost is set by the administrator on each port

  2. The bridges continue to advertise themselves as root bridges until they receive a CBPDU containing info about a better candidate. The bridge receiving a CBPDU containing a better candidate forwards this CBPDU out the other interface, after adding those interfaces' costs to the cost of the interface the CBPDU was originally sent from.
    (Cumbersome? yes! but I couldn’t come up with a better way to write it)

  3. When the bridges don't receive any more CBPDUs, the bridges choose the bridge with the lowest cost link as the root port. The designated bridge is the bridge that has links to other parts of the network.
    NOTE: If to bridges has the same cost, the bridge with the lowest MAC Address of those, is elected as the root bridge
Now that a root bridge has been selected, the interfaces on the bridges are put in either Forwarding State (FS) or Blocking State (BS). The interfaces that are in BS will not forward any packets, while those in FS will. Here are the rules:
  • An interface that is a part of the path with the lowest cost to the root bridge = FS.
  • All interfaces on the root bridge = FS
  • An interface that is a part of the path with the lowest cost to the designated bridge = FS
  • Any interface that doesn't match one of the above criteria’s = BS

After this is done, CBPDUs are sent once in a while in case changes in the topology have occurred. A change in the topology usually leads at least one interface changing from FS to BS or vice versa.