CSC263 Computer Networks

Computer NetworksUnit 616 min read

Application Layer – Services, Protocols, DNS & Socket Programming

Unit 6 of Computer Networks: introduces the application layer functions, key protocols (HTTP, FTP, SMTP, DNS, DHCP), socket programming with TCP/UDP, compares TCP/IP and OSI models, and explains DNS query types with examples.

Key points

  • The application layer provides end‑user services and hides lower‑layer complexities.
  • TCP offers reliable, connection‑oriented communication while UDP provides low‑latency, connectionless transport.
  • DNS translates domain names to IP addresses using recursive, iterative, and non‑recursive queries.
  • Socket APIs are the practical bridge between application programs and transport protocols.
  • Understanding the mapping between OSI and TCP/IP layers simplifies protocol analysis.

1. Introduction to the Application Layer

The application layer is the topmost layer in both the OSI (Layer 7) and TCP/IP (Application layer) models. Its primary purpose is to enable network‑aware applications to exchange data across heterogeneous hosts. It defines protocols, data formats, and interfaces that applications use, while abstracting the details of lower layers (transport, network, link, physical).

UApplication LayerTransport LayerProtocols (HTTP, DNS, FTP), Data formats, Session managementPorts (e.g., 80 for HTTP), SocketsTCP/UDP, Connection management, Flow controlPhysical/Link/Network layers
Application layer abstracts transport-layer details (e.g., TCP/UDP) while defining application-specific protocols.

Key responsibilities:

  • Service advertisement (e.g., “web server on port 80”).
  • Data representation (character encoding, MIME types).
  • Session management (establishing, maintaining, terminating dialogues).
  • Error handling and recovery (application‑level acknowledgments, retries).

Typical application‑layer protocols are HTTP, FTP, SMTP, DNS, DHCP, Telnet, POP3/IMAP, each designed for a specific class of services.


2. Core Application‑Layer Services

Service Description Typical Protocol(s) Default Port(s)
File Transfer Transfer of files between client and server FTP, TFTP, SFTP 21 (FTP), 69 (TFTP)
Remote Login Interactive command‑line access to remote host Telnet, SSH 23 (Telnet), 22 (SSH)
Electronic Mail Store‑and‑forward email delivery SMTP, POP3, IMAP 25 (SMTP), 110 (POP3), 143 (IMAP)
Web Services Retrieval of hypertext documents HTTP/HTTPS 80 (HTTP), 443 (HTTPS)
Name Resolution Mapping domain names to IP addresses DNS 53 (UDP/TCP)
Dynamic Host Configuration Automatic IP address assignment DHCP 67/68 (UDP)

These services are application‑specific; the underlying transport (TCP or UDP) is chosen based on reliability, ordering, and latency requirements.


3. TCP vs. UDP – When to Use Which

Feature TCP (Transmission Control Protocol) UDP (User Datagram Protocol)
Connection Connection‑oriented (three‑way handshake) Connectionless
Reliability Guarantees delivery, retransmission, duplicate suppression No guarantee; best‑effort
Ordering In‑order delivery via sequence numbers No ordering
Flow Control Sliding‑window flow control (receiver advertises window) None
Congestion Control Slow‑start, congestion avoidance, fast‑retransmit None
Overhead Higher (header = 20 bytes + ACKs) Lower (header = 8 bytes)
Typical Use Cases Web pages, email, file transfer, SSH DNS queries, streaming audio/video, VoIP, online gaming
graph LR
  TCP[TCP: Reliable, Ordered, Connection-Oriented] -->|Use for| Web(HTTP), Email(SMTP), File Transfer(FTP)
  UDP[UDP: Fast, Unreliable, Connectionless] -->|Use for| DNS, Streaming, VoIP, Gaming
  TCP -->|Features| SYN[3-Way Handshake], ACKs, Flow Control
  UDP -->|Features| No Handshake, No ACKs, Low Overhead

TCP vs. UDP: Key differences and typical use cases.

Worked Example: Simple UDP Echo Client/Server

# udp_echo_server.py
import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.bind(('0.0.0.0', 12345))
print('UDP echo server listening on port 12345')

while True:
    data, addr = sock.recvfrom(1024)      # receive datagram
    print(f'Received {data} from {addr}')
    sock.sendto(data, addr)              # echo back
# udp_echo_client.py
import socket

sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server = ('127.0.0.1', 12345)
message = b'Hello, UDP server!'
sock.sendto(message, server)

data, _ = sock.recvfrom(1024)
print('Received from server:', data.decode())
sock.close()

Diagram (textual)

Client                     Server
  |  sendto("Hello")  -->  |
  |                     recvfrom()
  |                     sendto("Hello")
  |  recvfrom()  <--      |

The client sends a single datagram; the server echoes it back. No connection setup, no ACKs—illustrating UDP’s simplicity.


4. Socket Programming – TCP and UDP

Sockets are the programming interface that bridges an application with the transport layer. In most languages (C, Java, Python) the API follows the same logical steps:

  1. Create a socket (socket()), specifying address family (AF_INET) and type (SOCK_STREAM for TCP, SOCK_DGRAM for UDP).
  2. Bind to a local address/port (server side).
  3. Listen (TCP only) and accept incoming connections.
  4. Connect (client side) to remote address (TCP).
  5. Send/Receive data (send(), recv(), sendto(), recvfrom()).
  6. Close the socket.

TCP Echo Server (Python)

import socket

HOST = ''          # listen on all interfaces
PORT = 50007

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.bind((HOST, PORT))
    s.listen(1)
    print(f'TCP echo server listening on port {PORT}')
    conn, addr = s.accept()
    with conn:
        print('Connected by', addr)
        while True:
            data = conn.recv(1024)
            if not data:
                break
            conn.sendall(data)   # echo back

TCP Echo Client (Python)

import socket

HOST = '127.0.0.1'   # server address
PORT = 50007

with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
    s.connect((HOST, PORT))
    s.sendall(b'Hello, TCP server!')
    data = s.recv(1024)

print('Received', repr(data))

Sequence diagram (ASCII)

Client                         Server
  |  connect() --------------> |
  |                           |  accept()
  |  send("Hello") ----------> |
  |                           |  recv()
  |                           |  send("Hello")
  | <------- recv() ---------- |
  |  close() ----------------> |

The three‑way handshake (SYN, SYN‑ACK, ACK) is performed implicitly by connect(). The server’s listen() queue holds pending connections, demonstrating TCP’s reliability and flow control.


5. DNS – The Internet’s Phone Book

1002003004005006007008009001000-10000-8000-6000-4000-2000200040006000800010000xDNS Query Latency (ms)Linear Lookup Latency (ms)Root ServerTLD ServerAuthoritative Server
DNS hierarchical resolution reduces latency compared to linear lookups (logarithmic scaling).

5.1 Why DNS Is Required

  • Humans remember domain names (e.g., www.example.com) but routers forward packets using IP addresses.
  • DNS provides a distributed, hierarchical database that maps names to addresses, supporting load balancing, redundancy, and dynamic updates.

5.2 DNS Query Types

Query Type Initiator Recursion Flag Typical Use
Recursive Resolver (usually stub resolver on client) Set (RD=1) Client expects final answer; resolver does all lookups.
Iterative Resolver (authoritative or caching) Not set (RD=0) Resolver returns best‑known answer (referral) and client follows referrals.
Non‑recursive Same as iterative; often used by authoritative servers to answer directly without further lookups.

5.3 DNS Resolution Walk‑through

Assume a client wants the A record for www.cs.tu.edu.np.

sequenceDiagram
  participant Client
  participant StubResolver
  participant RootServer
  participant TLDServers
  participant AuthoritativeServer

  Client->>StubResolver: Recursive Query (www.example.com)
  StubResolver->>RootServer: Iterative Query
  RootServer-->>StubResolver: Referral to .com
  StubResolver->>TLDServers: Iterative Query
  TLDServers-->>StubResolver: Referral to example.com
  StubResolver->>AuthoritativeServer: Iterative Query
  AuthoritativeServer-->>StubResolver: A Record (93.184.216.34)
  StubResolver-->>Client: Final Answer

DNS resolution walk-through: Recursive vs. iterative queries.

  1. Stub Resolver sends a recursive query to its configured caching resolver (e.g., ISP DNS).
  2. Caching resolver checks its cache; miss → sends an iterative query to a root server (.).
  3. Root server replies with a referral to the .np TLD servers.
  4. Resolver queries a .np server, receives referral to edu.np servers.
  5. Query to edu.np server yields referral to tu.edu.np authoritative servers.
  6. Query to tu.edu.np server returns the A record for www.cs.tu.edu.np.
  7. Resolver caches the answer and returns it to the client.

ASCII trace diagram

Client -> Resolver (RD=1)
Resolver -> Root (RD=0)          -> Referral: .np NS
Resolver -> .np NS (RD=0)        -> Referral: edu.np NS
Resolver -> edu.np NS (RD=0)     -> Referral: tu.edu.np NS
Resolver -> tu.edu.np NS (RD=0)  -> Answer: A = 203.0.113.45
Resolver -> Client (final answer)

5.4 DNS Record Types (selected)

Record Purpose Example
A IPv4 address www → 203.0.113.45
AAAA IPv6 address www → 2001:db8::1
CNAME Canonical name (alias) mail → mailhost.example.com
MX Mail exchange server example.com MX 10 mail.example.com
NS Authoritative name server example.com NS ns1.example.com
PTR Reverse lookup (IP → name) 45.113.0.203.in‑addr.arpa PTR www.example.com

6. Application Layer in the TCP/IP vs. OSI Models

Layer (OSI) Corresponding TCP/IP Layer(s) Primary Function
Application Application End‑user services (HTTP, DNS, SMTP)
Presentation Application Data representation, encryption, compression
Session Application Dialog control, synchronization
Transport Transport End‑to‑end reliability (TCP) or datagram service (UDP)
Network Internet Logical addressing, routing (IP)
Data Link Link MAC addressing, framing
Physical Physical Bit transmission over media

Key differences

  • OSI separates concerns into seven distinct layers, making the model more granular (Presentation, Session).
  • TCP/IP merges Presentation and Session into the Application layer, reflecting the practical implementation of the Internet protocol suite.
  • The OSI model is primarily a reference model; TCP/IP is a protocol suite that has been widely deployed.

7. Advantages of a Layered Architecture

  1. Modularity – Each layer can be designed, implemented, and upgraded independently.
  2. Interoperability – Standardized interfaces allow heterogeneous hardware/software to communicate.
  3. Simplified Troubleshooting – Problems can be isolated to a specific layer using the “layer‑by‑layer” approach.
  4. Scalability – New protocols can be added at a particular layer without affecting others (e.g., introducing HTTP/2 at the application layer).
  5. Reusability – Lower‑layer services (e.g., IP routing) are reused by many upper‑layer applications.

8. Representative Application‑Layer Protocols – Detailed View

8.1 HTTP/HTTPS

  • Stateless request/response protocol for hypertext.
  • Methods: GET, POST, PUT, DELETE, HEAD, OPTIONS.
  • Status codes: 200 OK, 404 Not Found, 500 Internal Server Error, etc.
  • HTTPS adds TLS encryption (layered on top of TCP).

Example HTTP GET transaction

Client:  GET /index.html HTTP/1.1
         Host: www.example.com
         User-Agent: Mozilla/5.0
         Connection: close

Server:  HTTP/1.1 200 OK
         Date: Sun, 25 Sep 2026 08:15:00 GMT
         Content-Type: text/html; charset=UTF-8
         Content-Length: 1256

         <html> … </html>

8.2 FTP

  • Control connection (TCP port 21) for commands.
  • Data connection (active: server‑initiated on port 20; passive: client‑initiated on a random high port).
  • Supports binary and ASCII modes, resume, directory listing.

8.3 SMTP / POP3 / IMAP

  • SMTP (port 25): push email from client to server or between mail servers.
  • POP3 (port 110): download mail to local client, usually deleting from server.
  • IMAP (port 143): remote mailbox management, supports folder hierarchy and concurrent access.

8.4 DHCP

  • Four‑message exchange: DHCPDISCOVER → DHCPOFFER → DHCPREQUEST → DHCPACK.
  • Provides IP address, subnet mask, default gateway, DNS servers to hosts automatically.

9. Worked Example: HTTP over TCP – End‑to‑End Trace

Assume a client on 192.168.1.10 requests http://example.com/page.html.

  1. DNS resolution (as described in Section 5) yields 93.184.216.34.
  2. TCP three‑way handshake
Client → SYN (seq=100) → Server
Server → SYN‑ACK (seq=200, ack=101) → Client
Client → ACK (seq=101, ack=201) → Server
  1. HTTP request (sent on the established TCP stream)
GET /page.html HTTP/1.1\r\n
Host: example.com\r\n
Connection: close\r\n\r\n
  1. Server response
HTTP/1.1 200 OK\r\n
Date: Sun, 25 Sep 2026 08:20:00 GMT\r\n
Content-Type: text/html\r\n
Content-Length: 342\r\n\r\n
<html> … </html>
  1. TCP connection termination (FIN/ACK exchange).

The trace demonstrates how the application layer (HTTP) relies on transport (TCP) for reliable delivery, and on network (IP) for routing.


10. Comparison Table: Application‑Layer Protocol Characteristics

Protocol Transport Used Port(s) Reliability Requirement Typical Payload Example Use
HTTP/HTTPS TCP 80 / 443 High (complete page needed) Text, HTML, JSON, binary Web browsing
FTP TCP (control) + TCP/UDP (data) 21 (control), 20 (active data) High (file integrity) Files (any type) File transfer
DNS UDP (most queries) / TCP (zone transfers) 53 Low (single query) Small name‑to‑IP mappings Name resolution
DHCP UDP 67 (server), 68 (client) Low (configuration) IP configuration parameters Auto IP assignment
SMTP TCP 25 (or 587) High (mail delivery) Email message (text, attachments) Sending email
POP3 TCP 110 High (mail retrieval) Email messages Download mail
IMAP TCP 143 High (mail sync) Email messages, flags Server‑side mail access

11. Common Exam Questions – How to Answer

Question Type Key Points to Mention Marks Allocation Tips
Socket programming (UDP/TCP) Show code skeleton, explain socket(), bind(), listen(), accept(), connect(), send/recv calls, and diagram of message flow. 2 marks for API steps, 2 marks for diagram, 1 mark for explanation of reliability vs. speed.
TCP/IP vs. OSI Map each OSI layer to TCP/IP, note merged layers, discuss why the models differ. 1 mark per correct mapping (7), 2 marks for concise comparison.
IP address classification (/27) Compute network address (192.16.144.64), broadcast (192.16.144.95), host range (65‑94). Identify given address (e.g., 192.16.144.70 is a host). 1 mark for network calc, 1 mark for broadcast, 1 mark for host identification.
Layered architecture advantages List modularity, interoperability, troubleshooting, scalability, reusability. 1 mark per valid advantage (max 5).
DNS query types Define recursive, iterative, non‑recursive; illustrate with a step‑by‑step resolution example. 1 mark per definition, 2 marks for example trace.

12. Summary

The application layer is the gateway through which users interact with the network. It hosts a rich set of protocols, each tailored to specific services, and relies on socket APIs to bind applications to transport mechanisms (TCP for reliability, UDP for speed). Understanding DNS is essential because name resolution underpins every higher‑level request. The layered architecture simplifies design, promotes interoperability, and eases troubleshooting—principles reflected in both the OSI and TCP/IP models.


Exam tip

  • Memorize the port numbers for the most common application protocols; they are frequently asked in short‑answer questions.
  • When a question asks for a socket program, write a minimal but complete code snippet (include import, socket creation, bind/connect, send/receive, close) and accompany it with a concise ASCII diagram showing the direction of messages.
  • For TCP/IP vs. OSI, draw a side‑by‑side table; the exam often rewards a clear visual mapping.
  • In DNS questions, explicitly state the recursion flag (RD) and walk through each referral step; a 5‑step trace earns full credit.
  • Always link the layer’s responsibilities to the protocol’s characteristics (e.g., “HTTP uses TCP because a complete web page must be delivered without loss”).

Based on the TU BSc CSIT syllabus for Computer Networks (CSC263), unit 6.

Discussion

Loading…