While Layers 2 and 3 allow addressing of hosts (directly connected or located anywhere in the Internet), the Transport Layer addresses applications on a host, e.g. a web- or mail-server.
The following image depicts that:
We can see an IPv6 packet that arrives at a server somewhere in the Internet, addressed via its IPv6 address. However, relying only on Layer 2/3 information the server does not know what to actually do with the packet next, respectively whether a webserver, mailserver, DNS or other software it is running is addressed.
Layer 4 solves that issue by adding Ports, which address specific applications on a host. The sender also chooses a port (usually randomly), which can be used to send responses to.
The ports 0-1023 are so-called well-known ports and reserved to specific applications or protocols. For example, in the following image the IPv6 packet uses the destination port 80, which is reserved for the HTTP protocol. The server therefore forwards the packet to a webserver application (e.g. apache2) listening to this port.
The two most relevant Layer 4 protocols are UDP and TCP, which offer different levels of reliability.
UDP has a very small additional header and very low overhead. However, it doesn’t guarantee that packets arrive at the destination or have the correct order.
TCP on the other hand offers both these properties and guarantees that packet arrive in the correct order at the receiving application. To achieve this, it has to establish a dedicated TCP connection and keep track of its state on both sides of the connection.
Those properties make UDP a good fit for applications where (some) packet loss is acceptable, as e.g. video streaming. TCP on the other hand is a good fit where packet loss is not acceptable, e.g. for transferring files where a single missing packet could corrupt the whole file.
Learn more about UDP and TCP in Part 4 of our free Massive Open Online Course:
There you also have the opportunity to do some experiments on Layer 4 using your own computer and our virtual network environment, e.g. observe what happens to packets sent via UDP/TCP over a connection with a certain packet loss: