0% found this document useful (0 votes)
11 views27 pages

Application Layer Protocols Overview

The application layer handles services like video streaming, email, and web services, utilizing socket APIs for communication. It includes common protocols like HTTP, SMTP, and DNS, and operates under client-server and peer-to-peer models. Key features include addressing processes with IP and port numbers, the use of TLS for security, and the evolution of HTTP to versions 2 and 3 for improved performance and reduced latency.

Uploaded by

whyetb31
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views27 pages

Application Layer Protocols Overview

The application layer handles services like video streaming, email, and web services, utilizing socket APIs for communication. It includes common protocols like HTTP, SMTP, and DNS, and operates under client-server and peer-to-peer models. Key features include addressing processes with IP and port numbers, the use of TLS for security, and the evolution of HTTP to versions 2 and 3 for improved performance and reduced latency.

Uploaded by

whyetb31
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

🌐 Overview of the Application Layer

Video streaming, content distribution, email, DNS, and web services are all
handled at the application layer.
Programmers use socket APIs (both UDP and TCP) to implement these
services.
The layer sits above the transport layer and provides protocols that define
how messages are formatted and exchanged.

📡 Common Application‑Layer Protocols


HTTP – web page and object retrieval
SMTP – sending email
IMAP – retrieving email
DNS – translating domain names to IP addresses
FTP – file transfer (though often replaced by HTTP/HTTPS)
SIP / RTP – Internet telephony and media streaming

Definition: An application‑layer protocol specifies the message types, syntax,


semantics, and interaction rules that enable interoperable communication between
processes.

📱 Network Applications
Social media, VoIP, web browsing, video conferencing, text messaging, search
engines, remote login, multiplayer games, streaming services (YouTube, Netflix),
P2P file sharing, etc.

🖥️ Client‑Server Paradigm
Server: always‑on host with a permanent IP address, usually located in a data
center for scalability.
Client: may be intermittently connected, often behind a home or regional ISP,
and uses dynamic IP addresses.
Communication follows a request‑response pattern (e.g., browser → HTTP
request → web server → HTTP response).

Definition: In the client‑server model, a client process initiates communication, while a


server process waits to be contacted and responds to requests.
🤝 Peer‑to‑Peer Architecture
No dedicated always‑on server; peers act as both clients and servers.
New peers increase both service capacity and demand.
Example: BitTorrent file sharing.
Peers often have dynamic IPs and intermittent connectivity, making
management more complex.

Definition: Peer‑to‑peer (P2P) systems consist of arbitrary end systems that directly
exchange services and data without a central server.

🔌 Processes and Sockets


A process is a running program on a host.
A socket is the endpoint through which a process sends or receives messages,
analogous to a door.
Two sockets are required for a communication session: one on the sender side,
one on the receiver side.

📍 Addressing Processes (IP & Port)


Each process is identified by a pair: IP address + port number.
Example:
HTTP server → port 80
Mail server → port 25
Multiple processes can run on the same host (same IP) but must listen on
different ports.

📄 Application‑Layer Protocol Definition (Recap)


Message types (e.g., request, response)
Message syntax (field layout, delimiters)
Message semantics (meaning of each field)
Interaction rules (when to send, how to respond)

📊 Transport Service Requirements


Application Type Loss Tolerance Throughput Needs Time Sensitivity
File transfer / No loss High Low
download
Email No loss Moderate Low
Web documents No loss Moderate Low
Real‑time audio Loss‑tolerant Low‑moderate Yes, tens of ms
(5 Kb/s–1 Mb/s)
Real‑time video Loss‑tolerant Moderate–high Yes, tens of ms
(10 Kb/s–5 Mb/s)
Interactive games Loss‑tolerant Moderate Yes, tens of ms
(Kbps+)
Text messaging No loss Low Yes, low latency

⚙️ Internet Transport Protocols: TCP vs UDP


Feature TCP UDP
Reliability Reliable Unreliable (no guarantees)
(acknowledgments,
retransmission)
Flow Control Yes (prevents receiver No
overload)
Congestion Control Yes (throttles sender on No
overload)
Connection‑oriented Yes (handshake required) No (connectionless)
Typical Use Cases File transfer, email, web Streaming media, VoIP,
pages online gaming
Guarantees Ordered delivery, Best‑effort delivery
error‑free data

🗺️ Mapping Applications to Transport Protocols


Application Protocol(s) Transport
FTP (file transfer) RFC 959 TCP
SMTP (email) RFC 5321 TCP
HTTP / HTTPS (web) RFC 7230, 9110 TCP
SIP / RTP (Internet RFC 3261, 3550 TCP or UDP
telephony)
DASH / streaming video RFC 7230 (HTTP) TCP (often)
Interactive games (e.g., Proprietary UDP (sometimes TCP)
FPS)

🔒 Securing TCP with TLS


Plain TCP sockets transmit data in cleartext (e.g., passwords).
TLS (Transport Layer Security) wraps the TCP connection, providing:
Encryption (confidentiality)
Data integrity (tamper detection)
Endpoint authentication (verifying server/client identity)

Definition: TLS creates an encrypted channel over a TCP socket, ensuring that the
data traversing the Internet cannot be read or altered by eavesdroppers.

🌍 Web and HTTP Basics


A web page is a collection of objects (HTML, images, scripts, audio, etc.), each
addressable by a URL.
HTTP operates over TCP and follows a stateless request‑response model:
1. Client opens a TCP connection to the server’s port 80 (or 443 for
HTTPS).
2. Client sends an HTTP request (e.g., GET /[Link]).
3. Server replies with an HTTP response containing status code,
headers, and the requested object.
Because HTTP is stateless, the server does not retain information about
previous client interactions unless higher‑level mechanisms (cookies, sessions)
are used.
## 🌐 HTTP Connection Types
Non‑persistent HTTP – a separate TCP connection is opened for each object.
Persistent HTTP (HTTP/1.1) – the TCP connection stays open; multiple objects
are fetched over the same connection, reducing the number of round‑trip times
(RTTs).

📦 Non‑Persistent HTTP Example


1️⃣ User enters URL [Link]/someDepartment/[Link] (HTML + 10
JPEGs).
2️⃣ TCP connection is opened to the server at port 80.
3️⃣ HTTP request (GET) is sent over the TCP connection.
4️⃣ Server replies with the requested HTML file and closes the TCP connection.
5️⃣ Client parses the HTML, discovers 10 image references.
6️⃣ Steps 1‑5 repeat for each JPEG, each requiring a new TCP connection.
⏱️ Response‑Time Analysis
Round‑Trip Time (RTT) – the time for a small packet to travel from client to server and
back.

Non‑persistent HTTP response time per object = 2RTT + file transmission


time
Persistent HTTP can deliver all referenced objects with as few as 1 RTT after
the first request, roughly halving the total response time.

🔁 Persistent HTTP Advantages


Aspect Non‑Persistent Persistent (HTTP/1.1)
TCP connections per 1 × object 1 × page (reused)
object
RTTs per object 2 RTTs 1 RTT for first object,
≤1 RTT for subsequent
OS overhead High (many sockets) Lower (socket reuse)
Parallel fetching Multiple connections Can pipeline requests on a
opened in parallel single connection

📧 HTTP Request Message


Two types of HTTP messages: request and response.
Request line format:

GET /[Link] HTTP/1.1\r\n

Common header fields (example):

Host: [Link]\r\n
User-Agent: Mozilla/5.0\r\n
Accept: text/html,application/xhtml+xml\r\n
Accept-Language: en-us\r\n
Accept-Encoding: gzip,deflate\r\n
Connection: keep-alive\r\n
\r\n

General Format

\r\n
: \r\n
...
\r\n
[entity‑body]

Common HTTP Methods


Method Typical Use
GET Retrieve a resource; parameters
appended to URL (?).
POST Submit data (e.g., form input) in the
request body.
HEAD Retrieve only header fields (no body).
PUT Upload a new version of a resource.

📬 HTTP Response Message


Starts with a status line:

HTTP/1.1 200 OK\r\n

Followed by header fields, a blank line, then the optional body.


Sample Headers

Date: Tue, 08 Sep 2020 [Link] GMT\r\n


Server: Apache/2.4.6 (CentOS)\r\n
Last-Modified: Tue, 01 Mar 2016 [Link] GMT\r\n
ETag: "a5b-52d015789ee9e"\r\n
Content-Length: 2651\r\n
Content-Type: text/html; charset=UTF-8\r\n
\r\n
[HTML content]

Status Codes
Code Phrase Meaning
200 OK Request succeeded; object
follows.
301 Moved Permanently Resource moved; new URL
in Location: header.
400 Bad Request Server could not
understand the request.
404 Not Found Requested document does
not exist.
505 HTTP Version Not Server does not support
Supported the HTTP version used.

Definition – Stateless Protocol: HTTP treats each request independently; the server
does not retain “state” between requests unless the client supplies it (e.g., via cookies).

🛠️ Trying HTTP with netcat


# macOS / Linux
nc -c -v [Link] 80
# Windows (ncat)
ncat -C [Link] 80

After the connection opens, type a minimal GET request (press Enter twice to terminate
the header):

GET /kurose_ross/interactive/[Link] HTTP/1.1


Host: [Link]

The server’s full response will be displayed, allowing you to inspect headers and body.

🍪 Cookies and State Management


Cookies embed a small identifier in HTTP headers to maintain user‑specific
state across otherwise stateless requests.
Four components involved:
1. Server‑generated Set‑Cookie header (unique ID).
2. Cookie stored in the client’s browser.
3. Cookie sent back in subsequent requests (Cookie: header).
4. Server‑side database mapping cookie IDs to user data.

Example Flow
1. User visits e‑commerce site → server replies with Set-Cookie: ID=1678.
2. Browser stores ID=1678.
3. Later request to the same site includes Cookie: ID=1678.
4. Server looks up ID=1678 in its database to retrieve the user’s session.

📊 Cookie Tracking Example


First‑party cookie (1634) set by [Link] to track the user’s interests (e.g.,
“sports”).
Third‑party cookie (7493) set by an ad network ([Link]) when the page
loads an embedded ad.
Cookie ID Owner Purpose
1634 [Link] Store user’s content
preferences.
7493 [Link] Track browsing across sites
for targeted advertising.
The browser automatically includes both cookies in subsequent requests, enabling
🍪
personalized content and ads.## Cookies & Tracking
Cookies store small pieces of data on a user’s device to identify sessions and
track behavior.
First‑party cookies → set by the website the user visits (e.g., NY Times).
Third‑party cookies → set by external domains (e.g., ad networks) and can
follow a user across multiple sites without any direct visit to the tracker.

Definition: Third‑party tracking occurs when a site embeds resources (images, scripts,
invisible links) that cause the browser to send a request to a domain other than the one
shown in the address bar, allowing that domain to set/read cookies.

Many browsers disable third‑party cookies by default (Firefox, Safari) and


plan to do so in Chrome (2023).
Tracking Type Set By Visibility to User Typical Use
First‑party Visited site Visible (e.g., session Session
cookie) management
Third‑party Embedded tracker Often invisible (e.g., Advertising,
1×1 pixel) analytics

🛡️ GDPR & Cookies (EU)


“Natural persons may be associated with online identifiers … such as … cookie
identifiers … which may be used to create profiles …” – GDPR Recital 30 (May 2018)

Personal data under GDPR includes any identifier that can be linked to an
individual, including cookie IDs.
Users must give explicit consent before cookies that can identify them are
stored.
Organizations must treat cookie data as subject to GDPR compliance (rights
to access, delete, restrict processing).

📦 Web Caches (Proxy Servers)


A web cache sits between browsers and origin servers.
Workflow:
1. Browser sends request to cache.
2. If object is cached → cache returns it directly.
3. If not → cache fetches from origin, stores a copy, then forwards to
browser.

Goal: Satisfy client requests without involving the origin server whenever possible,
reducing latency and network traffic.

Benefits:
Lower response time (cache is closer to client).
Decreased backbone traffic.
Enables “poor” content providers to serve users efficiently.
📊 Caching Performance Analysis
Scenario Parameters
Access link rate: 1.54 Mbps
RTT (router ↔ server): 2 s
Web object size: 100 Kbits
Avg. request rate: 15 requests / s
Avg. data rate to browsers: 1.50 Mbps

Option 1 – Faster Access Link (154 Mbps)


Metric Value
Utilization (old link) ​
Utilization (154 Mbps) ​
End‑to‑end delay (approx.) ​
Cost High (upgraded link)

Option 2 – Install a Web Cache


Assume cache hit rate = 0.4.
Traffic over access link =
Utilization = (much lower than 0.97).
Average end‑to‑end delay

Result: A cheap cache yields lower utilization and shorter average delay than buying
a 154 Mbps link.

📄 Browser Caching: Conditional GET


Goal: Avoid sending the full object when the browser already has a fresh copy.
Process (HTTP/1.0)
1. Client includes If-Modified-Since: header in request.
2. Server checks the object's last‑modified time.
If unchanged → responds 304 Not Modified (no body).
If changed → responds 200 OK with the new object.

Benefit: Saves bandwidth and reduces latency by eliminating unnecessary data


transfers.

🔗 HTTP/2 Overview
Designed to reduce delay for multi‑object requests.
Introduces multiplexing: multiple streams share a single TCP connection.
Allows server‑initiated pushes and prioritized frames (not strict FCFS).

HOL (Head‑of‑Line) Blocking Mitigation


HTTP/1.1 HTTP/2
Requests processed sequentially; a large Objects split into frames; frames from
object can stall smaller ones. different streams interleaved, so small
objects can progress while large ones
transmit.

🌐 HTTP/3 & QUIC


HTTP/3 runs over QUIC, a transport protocol built on UDP.
Provides:
Integrated TLS (security built‑in).
Per‑object loss and congestion control, avoiding the
“all‑or‑nothing” stall of TCP.
Faster connection establishment (1‑RTT or 0‑RTT).
QUIC Highlights
Feature TCP (HTTP/1.1/2) QUIC (HTTP/3)
Handshake rounds 3‑way TCP + TLS (2 RTT) 1‑RTT (or 0‑RTT)
Congestion control TCP algorithms only TCP‑like algorithms plus
UDP flexibility
Reliability In‑band (TCP) Built‑in at QUIC layer
Security Separate TLS layer TLS 1.3 integrated

🚀 QUIC Connection Establishment


1. 1‑RTT Handshake
Client sends ClientHello (includes TLS).
Server replies with ServerHello, completes TLS and QUIC handshake
in the same round‑trip.
2. 0‑RTT Handshake (when a previous session ticket exists)
Client reuses a TLS session ticket from a prior connection.
Sends encrypted data immediately; server validates ticket and
proceeds without extra RTT.

Result: Connection is ready for data transmission after one (or even zero) round‑trips,
dramatically cutting latency.

📚 Application Layer Overview


Core services: video streaming, content distribution, email, DNS, socket
programming.
Key protocols:
HTTP/1.x, HTTP/2, HTTP/3 (web).
SMTP, IMAP (email).
DNS (name resolution).
Supports both TCP (reliable) and UDP (low‑latency) transports, depending on
application needs.
✉️ E‑mail Architecture
Component Role
Mail User Agent (MUA) Interface for users (e.g., Outlook, Gmail
web UI).
Mail Transfer Agent (MTA) Handles SMTP routing between servers.
Mail Delivery Agent (MDA) Stores incoming mail in the user’s mailbox
(often via IMAP/POP).
Typical flow: MUA → SMTP (MTA) → SMTP (remote MTA) → MDA → MUA.## 📧
Simple Mail Transfer Protocol (SMTP) Overview
User Agent (UA) – mail client (e.g., Outlook, iPhone Mail) used for composing,
editing, and reading messages.
Mail Server – stores incoming messages in a mailbox and outgoing messages
in a message queue.
SMTP – protocol that moves mail from the sending server’s queue to the
receiving server’s mailbox.

Definition: SMTP (Simple Mail Transfer Protocol) is the application‑layer protocol


defined in RFC 5321 that transfers email messages between mail servers.

SMTP Roles
Role Description
Client The sending mail server that initiates a
TCP connection (port 25).
Server The receiving mail server that accepts the
connection and stores the message.

Connection Flow
1. Sending server opens a TCP connection to the receiving server (port 25).
2. Three phases occur: handshake, message transfer, closure.
3. Interaction follows a command/response pattern similar to HTTP.

📨 SMTP Handshake & Transfer Phases


Phase Server Response Client Command
Greeting 220 Service ready HELO
Sender verification 250 OK MAIL FROM:
Recipient verification 250 OK RCPT TO:
Data transmission 354 Start mail input DATA → message body → .
Quit 221 Service closing QUIT

📂 Sample SMTP Interaction


S: 220 [Link]
C: HELO [Link]
S: 250 Hello [Link], pleased to meet you
C: MAIL FROM:
S: 250 alice@[Link]... Sender ok
C: RCPT TO:
S: 250 bob@[Link] ... Recipient ok
C: DATA
S: 354 Enter mail, end with "." on a line by itself
C: Do you like ketchup?
C: How about pickles?
C: .
S: 250 Message accepted for delivery
C: QUIT
S: 221 [Link] closing connection

🔄 SMTP vs. HTTP Comparison


Connection type: SMTP uses persistent connections; HTTP traditionally uses
request/response (client pull).
Data flow: SMTP pushes the full message (header + body) in 7‑bit ASCII; HTTP
delivers objects one at a time.
Both employ ASCII command/response messages and status codes.
SMTP can send multipart messages (multiple objects) within a single session;
HTTP sends each object in a separate response.

📨 Mail Message Format


Defined by RFC 2822 (syntax of the email itself).
Header lines (outside SMTP commands) include:
To:
From:
Subject:
Body – the actual message content, limited to ASCII characters for SMTP
transmission.

📥 Retrieving Email: Mail Access Protocols


Protocol Primary Use Key Features
IMAP (RFC 3501) Retrieve, delete, and Supports folders,
organize messages stored server‑side search, multiple
on a server clients
POP3 Simple Minimal state, best for
download‑and‑delete single‑device access
retrieval
HTTP‑based webmail Web interface built on top Provides UI in browsers;
(e.g., Gmail) of SMTP + IMAP/POP SMTP used for sending

Definition: SMTP handles delivery/storage to the receiver’s server, while IMAP/POP3


(or webmail) handle retrieval from that server.

🌐 Application Layer Overview


Core services: video streaming, web/HTTP, email (SMTP, IMAP), DNS.
Underlying transport: TCP (reliable) and UDP (low‑latency).
Programming focus: socket APIs, protocol implementations, distributed
databases.

🌍 Domain Name System (DNS) Basics


Purpose: Translate human‑readable domain names (e.g., [Link]) to IP
addresses (32‑bit).
Implemented as a distributed, hierarchical database of resource records
(RRs).
Operates as an application‑layer protocol.

Definition: DNS is the Internet’s “phone book,” mapping names to IP addresses


through a network of authoritative and caching name servers.

🗂 DNS Services & Structure


Why not centralized?
Single point of failure.
Massive traffic volume (trillions of queries per day).
Need for load distribution, aliasing, and local administration.
Hierarchy:
1. Root servers – top of the tree, point to TLD servers.
2. Top‑Level Domain (TLD) servers – manage .com, .org, country
codes, etc.
3. Authoritative servers – hold actual records for a domain (e.g.,
[Link]).
4. Local (recursive) resolvers – ISP or corporate DNS servers that
cache results for clients.

🔁 DNS Query Types


Query Type Behavior
Iterative Resolver receives a referral from each
server and contacts the next server itself.
Recursive Resolver asks the first server to fully
resolve the name; the server does the
iteration on behalf of the client.

🧩 DNS Record Types


Type Meaning
A IPv4 address of a hostname.
CNAME Canonical name; an alias pointing to
another hostname.
MX Mail exchange server for the domain.
NS Authoritative name server for the zone.
TTL (Time‑to‑Live) Duration a cached record is considered
valid.

🗃 Caching in DNS
Any name server that learns a mapping stores it in a cache for the record’s TTL.
Benefits: Faster responses, reduced load on upper‑level servers.
Drawbacks: Possible staleness if a host’s IP changes before TTL expires.

🏢 DNS Management Entities


ICANN – Oversees the root zone and overall DNS policy.
Root server operators – 13 logical root zones, each replicated globally.
TLD registries (e.g., Network Solutions for .com, Educause for .edu).
Organization’s authoritative servers – Serve the domain’s own records, can
be self‑hosted or delegated to a provider.

Key Takeaways
SMTP moves mail between servers using a simple, ASCII‑based
command/response protocol over TCP.
IMAP/POP3 (or webmail) retrieve stored messages for end users.
DNS is a massive, distributed name‑to‑address service organized hierarchically
with caching to ensure speed and scalability.
These components together form the backbone of modern Internet communication at the
🌐
application layer.## DNS Records & Queries
A record – maps a domain name to its IPv4 address.
NS record – specifies the authoritative name server for a domain.
MX record – identifies the mail exchange server for a domain.

Definition: Canonical name – the official, unique name for a resource in DNS.
Record Type Name Example Value Example
A [Link] [Link]
NS [Link] [Link]
MX [Link] [Link]
(SMTP)

DNS Message Format


Both queries and replies share the same header structure (12 bytes total):
Field Size (bits) Purpose
Identification 16 Matches replies to queries
Flags 16 QR, opcode, AA, TC, RD,
RA, Z, RCODE
QDCOUNT 16 Number of questions
ANCOUNT 16 Number of answer RRs
NSCOUNT 16 Number of authority RRs
ARCOUNT 16 Number of additional RRs
Question Section – contains name and type fields for each query.
Answer Section – resource records answering the query.
Authority Section – records for authoritative name servers.
Additional Section – supplemental info (e.g., IPs of name servers).

🛡️ DNS Security Threats


DDoS attacks – flood root or TLD servers with massive traffic.
Spoofing attacks – intercept queries and inject bogus replies.
Cache poisoning – attempt to insert false records into DNS caches (rarely
successful).
RFC 4033 – DNSSEC – adds authentication to DNS responses.
Local DNS caching – reduces load on root servers but can be a target for
attacks on TLD servers.
📺 Video Streaming & CDNs
Why Streaming Is Challenging
Bandwidth‑intensive: accounts for ~80 % of residential ISP traffic (2020).
Scale: must serve ~1 billion users.
Heterogeneity: diverse device capabilities and network conditions.

Video Coding Basics


Spatial coding – compresses each frame by exploiting redundancy within the
image.
Temporal coding – transmits only differences between consecutive frames.
Coding Type Rate Type Typical Bitrate Example Standard
(Mbps)
CBR (Constant Bit Fixed 1.5 (MPEG‑1) – 6 DVD, CD‑ROM
Rate) (MPEG‑2)
VBR (Variable Bit Adaptive 0.064 – 12 MPEG‑4, DASH
Rate)

Adaptive Streaming (DASH)


1. Server slices video into small chunks, each encoded at multiple bitrates.
2. Manifest file lists URLs for all chunks and their bitrate options.
3. Client repeatedly:
Estimates current bandwidth.
Chooses the highest sustainable bitrate.
Requests the next chunk (possibly from a nearby CDN node).

Key Insight: The intelligence resides in the client, which balances buffering, quality,
and server selection.

Content Distribution Networks (CDNs)


Goal: Deliver popular content to many users with low latency and high
reliability.
Approach 1 (single mega‑server): Not scalable; suffers from congestion and
single point of failure.
Approach 2 (distributed CDN): Replicates content across many geographically
dispersed edge servers.
Example: Akamai – >240 k servers in >120 countries (2015).
Example: Limelight – clusters in POPs near access networks.

OTT (Over‑the‑Top) Streaming


Challenge: Choose optimal CDN node and bitrate despite congested Internet
paths.
Netflix Model: Stores content in its global OpenConnect CDN; client fetches
manifest, then streams at the best reachable rate.

🖧 Application‑Layer Overview
P2P applications
Network principles
Video streaming & CDNs
Web & HTTP
Socket programming
E‑mail (SMTP, IMAP)
UDP & TCP
Domain Name System (DNS)

🖥️ Socket Programming Basics


Socket: Interface between an application process and the transport layer
(TCP/UDP).
Two socket types:
UDP – unreliable, message‑oriented datagrams.
TCP – reliable, byte‑stream service.

Process Flow Example:


1. Client reads a line from the keyboard and sends it.
2. Server receives the line, converts characters to uppercase, and returns the
result.

---## 📡 UDP: Connection‑less Transport


UDP (User Datagram Protocol) provides unreliable transfer of datagrams between
client and server processes. No handshaking, no guarantee of delivery or ordering.
No connection establishment before sending data.
Sender must attach destination IP address and port to each packet.
Receiver extracts sender’s IP address and port from the received packet.
Transmitted data may be lost or arrive out‑of‑order.

UDP Socket Interaction (Client ↔ Server)


1. Create sockets (both client and server) with socket(AF_INET, SOCK_DGRAM).
2. Server binds its socket to a local port: [Link](('', port)).
3. Client sends a datagram with sendto(message, (serverIP, port)).
4. Server receives with recvfrom(bufsize) → obtains message + client address.
5. Server replies using sendto(reply, clientAddress).
6. Close sockets when done.

Example: UDP Client (Python)

# udp_client.py
from socket import *

server_name = 'hostname' # server host name or IP


server_port = 12000

client_socket = socket(AF_INET, SOCK_DGRAM)

msg = input('Input lowercase sentence: ')


client_socket.sendto([Link](), (server_name, server_port))

modified_msg, server_addr = client_socket.recvfrom(2048)


print(modified_msg.decode())

client_socket.close()

Example: UDP Server (Python)

# udp_server.py
from socket import *

server_port = 12000
server_socket = socket(AF_INET, SOCK_DGRAM)
server_socket.bind(('', server_port))
print('The server is ready to receive')
while True:
msg, client_addr = server_socket.recvfrom(2048)
reply = [Link]().upper()
server_socket.sendto([Link](), client_addr)

🐍 TCP: Connection‑oriented, Reliable Transport


TCP (Transmission Control Protocol) delivers a reliable, in‑order byte‑stream (“pipe”)
between client and server. Connection setup and teardown are handled automatically.

Server must be running before a client can connect.


Server creates a listening socket, then for each incoming request a new socket
is created (allowing multiple simultaneous clients).
Connection establishment uses a three‑way handshake; termination uses a
four‑step exchange (not shown here).

TCP Socket Interaction (Client ↔ Server)


1. Server creates a listening socket: socket().
2. Server binds to a port and calls listen(backlog).
3. Client creates a socket and calls connect((serverIP, port)).
4. Server accepts the connection: connectionSocket, addr =
[Link]().
5. Both sides use send / recv on the connection socket.
6. Close the connection socket; the listening socket stays open for new clients.

Example: TCP Client (Python)

# tcp_client.py
from socket import *

server_name = 'servername'
server_port = 12000

client_socket = socket(AF_INET, SOCK_STREAM)


client_socket.connect((server_name, server_port))

sentence = input('Input lowercase sentence: ')


client_socket.send([Link]())

modified = client_socket.recv(1024)
print('From Server:', [Link]())

client_socket.close()

Example: TCP Server (Python)

# tcp_server.py
from socket import *

server_port = 12000
welcome_socket = socket(AF_INET, SOCK_STREAM)
welcome_socket.bind(('', server_port))
welcome_socket.listen(1)

print('The server is ready to receive')


while True:
conn_socket, addr = welcome_socket.accept()
sentence = conn_socket.recv(1024).decode()
reply = [Link]()
conn_socket.send([Link]())
conn_socket.close() # close only the connection socket

⚖️ UDP vs. TCP Comparison


Feature UDP TCP
Connection None (connectionless) Established via three‑way
handshake
Reliability Unreliable, possible Reliable, retransmission,
loss/out‑of‑order in‑order delivery
Overhead Low (no handshaking, Higher (handshake,
minimal headers) sequence numbers, ACKs)
Use Cases Streaming, DNS, VoIP, File transfer, web pages,
gaming email, SSH
Socket API (Python) SOCK_DGRAM SOCK_STREAM
Typical Code Calls sendto / recvfrom connect / accept → send /
recv

⏱️ Socket Timeouts & Exception Handling


Timeouts let a program stop waiting for a socket operation after a specified interval,
raising a timeout exception.

[Link](seconds) applies to all future operations on that socket.


settimeout(None) removes the timeout (blocks indefinitely).
settimeout(0) makes the socket non‑blocking.
Typical Pattern

import socket

s = [Link](socket.AF_INET, socket.SOCK_STREAM)
[Link](10) # 10‑second timeout for all ops
try:
[Link](('[Link]', 80))
[Link](b'GET / HTTP/1.0\r\n\r\n')
data = [Link](4096)
except [Link]:
print('Operation timed out!')
finally:
[Link]()

Multi‑event Waiting
select() – wait on multiple sockets for readability/writeability.
Multithreading – each socket handled in its own thread.
Frequently used in servers that must handle many clients or combine I/O with
timers.

📧 SMTP Interaction Example


S: 220 [Link]
C: HELO [Link]
S: 250 Hello [Link], pleased to meet you
C: MAIL FROM:
S: 250 alice@[Link]... Sender ok
C: RCPT TO:
S: 250 bob@[Link]... Recipient ok
C: DATA
S: 354 Enter mail, end with "." on a line by itself
C: Do you like ketchup?
C: How about pickles?
C: .
S: 250 Message accepted for delivery
C: QUIT
S: 221 [Link] closing connection

Sequence illustrates the request‑response nature of SMTP.


Each client command receives a numeric reply code from the server.

🌐 CDN Content Access Flow


1. Bob obtains a video URL from [Link].
2. His resolver looks up [Link] → receives a CNAME pointing to
[Link].
3. Bob’s browser requests the video from the KingCDN edge server (closest to
him).
4. The CDN serves the video, reducing latency and backbone load.

Key idea: CDNs use DNS redirection (CNAME) to map a content request to the
nearest cache server.

📺 Netflix Case Study: Multi‑CDN & Adaptive Streaming


Upload Phase: Netflix stores multiple video versions (different bitrates) in
Amazon‑cloud storage.
Registration: CDN servers register with Netflix’s accounting system.
Manifest File: Client receives a manifest (e.g., DASH) listing available
representations and CDN URLs.
Selection: The player selects a CDN and bitrate based on current network
conditions, then streams.

Takeaway: Modern video services combine cloud storage, CDN replication, and
adaptive streaming to deliver high‑quality video with minimal buffering.

📚 Chapter 2 Summary Highlights


Application architectures: client‑server, P2P, DNS, HTTP, SMTP, video
streaming.
Service requirements: reliability, bandwidth, delay, scalability, statefulness.
Transport models: TCP (reliable, connection‑oriented) vs. UDP (unreliable,
datagram).
Socket programming: create sockets, bind, listen/accept (TCP) or
sendto/recvfrom (UDP), handle timeouts, use select()/threads for concurrency.
Core themes: request/reply exchange, centralized vs. decentralized, stateless
vs. stateful, reliability vs. unreliability, edge‑side complexity.

You might also like