Protocol layers and encapsulation

Network software is organized in layers, where each layer provides a service to the one above and uses the one below. The Internet's TCP/IP model has four: the link layer moves frames between neighbouring devices, the internet layer (IP) moves packets between hosts across networks, the transport layer (TCP or UDP) connects processes on those hosts using port numbers, and the application layer holds protocols such as HTTP and DNS. The OSI reference model splits the same ideas into seven layers and is mainly used as a teaching vocabulary.

Python
def encapsulate(payload):
    segment = {"src_port": 50000, "dst_port": 80, "data": payload}
    packet = {"src_ip": "192.0.2.10", "dst_ip": "198.51.100.7", "data": segment}
    frame = {"src_mac": "aa:aa:aa:aa:aa:01", "dst_mac": "bb:bb:bb:bb:bb:02", "data": packet}
    return frame


def decapsulate(frame):
    packet = frame["data"]
    segment = packet["data"]
    return segment["data"]


frame = encapsulate("GET /")
print(list(frame))
print(frame["data"]["dst_ip"], frame["data"]["data"]["dst_port"])
print(decapsulate(frame))
Read the full lesson