STP (Spanning Tree Protocol) prevents loops in networks with multiple connected switches by using the IEEE 802.1D standard and BPDUs to manage port states. It establishes a root bridge based on the lowest bridge ID and assigns port roles (designated, root, non-designated, and disabled) to maintain a loop-free topology. Five port states (blocking, listening, learning, forwarding, and disabled) guide STP's operation, each with specific timing and functional criteria for handling data frames.