A router works by having a unique address on each port and a map of the network in an internal table. The router reads a packet from an incoming port, looks it up in the table , and sends it out the appropriate port.
There are a number of protocols for managing the network address tables of the routers.
A Bridge is similar to a router but no address table is used. All traffic in one port goes out the other port.