0% found this document useful (0 votes)
7 views35 pages

Uniy-2 CN 1 Notes

The document provides an overview of the Application Layer in computer networks, detailing client-server and peer-to-peer architectures, inter-process communication, and the concept of sockets. It discusses transport services, application layer protocols like HTTP, FTP, and DNS, and explains the client-server model's advantages and disadvantages. Additionally, it covers HTTP request and response structures, status codes, and the role of cookies in maintaining stateful information in a stateless protocol.

Uploaded by

Ravindra Bangari
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)
7 views35 pages

Uniy-2 CN 1 Notes

The document provides an overview of the Application Layer in computer networks, detailing client-server and peer-to-peer architectures, inter-process communication, and the concept of sockets. It discusses transport services, application layer protocols like HTTP, FTP, and DNS, and explains the client-server model's advantages and disadvantages. Additionally, it covers HTTP request and response structures, status codes, and the role of cookies in maintaining stateful information in a stateless protocol.

Uploaded by

Ravindra Bangari
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
You are on page 1/ 35

Unit-2(computer networks-1)notes

The Application Layer is the topmost layer in the OSI and TCP/IP models, responsible for
providing network services directly to end-users and applications. It enables
communication between software applications running on different devices across a network.

1. Principles of Network Applications


Network applications operate based on several principles, including:

a) Client-Server and Peer-to-Peer (P2P) Architectures

There are two primary architectures used in network applications:

1. Client-Server Architecture:
o A centralized server provides services, while multiple clients request
services.
o The server is always on and has a fixed IP address.
o Clients communicate with the server but not with each other.
o Examples: Web Browsing (HTTP), Email (SMTP, IMAP, POP3), File
Transfer (FTP)
2. Peer-to-Peer (P2P) Architecture:
o There is no central server; instead, each peer (node) acts as both a client and
a server.
o Resources and services are distributed among peers.
o Examples: BitTorrent, Skype (earlier versions), Blockchain Networks

b) Communication Between Processes

A network application enables inter-process communication, where processes running on


different hosts exchange data. Two key concepts are:

 Client Process: Initiates communication by sending a request.


 Server Process: Waits for requests and responds accordingly.

2. The Concept of Sockets


A socket is an interface that allows communication between applications across a network. It
acts as an endpoint for sending and receiving data.

How Sockets Work?

 A client creates a socket and connects to the server.


 The server listens for incoming requests on a socket.
 The client and server exchange data through their respective sockets.

Example of a socket-based communication using Python:

python
CopyEdit
import socket

# Creating a client socket


client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect(("example.com", 80)) # Connect to server at port 80

3. Transport Services Available to the Application Layer


The Transport Layer provides services to applications using two primary protocols:

Feature TCP (Transmission Control Protocol) UDP (User Datagram Protocol)


Connection
Connection-oriented Connectionless
Type
Ensures data is received correctly and in
Reliability No guarantee of delivery or order
order
DNS, VoIP, Online Gaming,
Use Cases HTTP, FTP, Email, SSH
Streaming

Choosing Between TCP and UDP:

 Use TCP when reliability is important (e.g., web browsing, email).


 Use UDP when speed and low latency are important (e.g., live video streaming,
online gaming).

4. Application Layer Protocols


The Application Layer supports various protocols that provide specific services:

a) Web and HTTP

 Persistent vs. Non-Persistent Connections: Persistent connections reuse the same


TCP connection for multiple requests, reducing overhead.
 HTTP Message Format: Composed of request and response messages.
 Cookies: Used to store user information across sessions.
 Proxy Servers: Intermediate servers that handle requests on behalf of clients.
 Conditional GET: A method to reduce unnecessary data transfer by retrieving a
resource only if it has been modified.

b) File Transfer Protocol (FTP)


 FTP allows users to transfer files between computers.
 Uses two connections: Control Connection (commands) and Data Connection (file
transfer).

c) Email Services

 SMTP (Simple Mail Transfer Protocol): Handles email sending.


 POP3 & IMAP: Protocols for retrieving emails. IMAP allows syncing across
multiple devices, while POP3 downloads and deletes from the server.
 MIME (Multipurpose Internet Mail Extensions): Allows email attachments
(images, videos, etc.).

d) Domain Name System (DNS)

 Converts domain names (e.g., www.google.com) into IP addresses.


 Hierarchical structure includes: Root Servers → TLD Servers → Authoritative
DNS Servers.
 Uses Resource Records and DNS messages to store and query domain information.

e) Peer-to-Peer File Distribution (BitTorrent)

 Distributes files across multiple peers instead of a central server.


 Uses seeders (uploaders) and leechers (downloaders) to share data efficiently.

Client and Server processes,

The Client-server model is a distributed application structure that


partitions tasks or workloads between the providers of a resource or
service, called servers, and service requesters called clients. In the client-
server architecture, when the client computer sends a request for data to
the server through the internet, the server accepts the requested process
and delivers the data packets requested back to the client. Clients do not
share any of their resources. Examples of the Client-Server Model are
Email, World Wide Web, etc.

 Client: When we say the word Client, it means to talk of a person or


an organization using a particular service. Similarly in the digital world,
a Client is a computer (Host) i.e. capable of receiving information or
using a particular service from the service providers (Servers).
 Servers: Similarly, when we talk about the word Servers, It means a
person or medium that serves something. Similarly in this digital world,
a Server is a remote computer that provides information (data) or
access to particular services.
So, it is the Client requesting something and the Server serving it as long
as it is in the database.

There are a few steps to follow to interacts with the


servers of a client.
 User enters the URL(Uniform Resource Locator) of the website or file.
The Browser then requests the DNS(DOMAIN NAME
SYSTEM) Server.
 DNS Server lookup for the address of the WEB Server.
 The DNS Server responds with the IP address of the WEB Server.
 The Browser sends over an HTTP/HTTPS request to the WEB
Server’s IP (provided by the DNS server).
 The Server sends over the necessary files for the website.
 The Browser then renders the files and the website is displayed. This
rendering is done with the help of DOM (Document Object Model)
interpreter, CSS interpreter, and JS Engine collectively known as
the JIT or (Just in Time) Compilers.

Advantages of Client-Server Model


 Centralized system with all data in a single place.
 Cost efficient requires less maintenance cost and Data recovery is
possible.
 The capacity of the Client and Servers can be changed separately.
Disadvantages of Client-Server Model
 Clients are prone to viruses, Trojans, and worms if present in the
Server or uploaded into the Server.
 Servers are prone to Denial of Service (DOS) attacks.
 Data packets may be spoofed or modified during transmission.
 Phishing or capturing login credentials or other useful information of
the user are common and MITM(Man in the Middle) attacks are
common.
Transport services available to Application Layer

Responsibilities of a Transport Layer


 The Process to Process Delivery
 End-to-End Connection between Hosts
 Multiplexing and Demultiplexing
 Congestion Control
 Data integrity and Error correction
 Flow control

1. The Process to Process Delivery


While Data Link Layer requires the MAC address (48 bits address
contained inside the Network Interface Card of every host machine) of
source-destination hosts to correctly deliver a frame and the Network
layer requires the IP address for appropriate routing of packets, in a
similar way Transport Layer requires a Port number to correctly deliver the
segments of data to the correct process amongst the multiple processes
running on a particular host. A port number is a 16-bit address used to
identify any client-server program uniquely.

2. End-to-end Connection between Hosts


The transport layer is also responsible for creating the end-to-end
Connection between hosts for which it mainly uses TCP and UDP. TCP is
a secure, connection-orientated protocol that uses a handshake protocol
to establish a robust connection between two end hosts. TCP ensures the
reliable delivery of messages and is used in various applications. UDP, on
the other hand, is a stateless and unreliable protocol that ensures best-
effort delivery. It is often used in multicasting protocols.
3. Multiplexing and Demultiplexing
Multiplexing(many to one) is when data is acquired from several
processes from the sender and merged into one packet along with
headers and sent as a single packet. Multiplexing allows the simultaneous
use of different processes over a network that is running on a host. The
processes are differentiated by their port numbers. Similarly,
Demultiplexing(one to many) is required at the receiver side when the
message is distributed into different processes. Transport receives the
segments of data from the network layer distributes and delivers it to the
appropriate process running on the receiver’s machine.

4. Congestion Control

Congestion is a situation in which too many sources over a network


attempt to send data and the router buffers start overflowing due to which
loss of packets occurs. As a result, the retransmission of packets from the
sources increases the congestion further.
5. Data integrity and Error Correction
The transport layer checks for errors in the messages coming from the
application layer by using error detection codes, and computing
checksums, it checks whether the received data is not corrupted and uses
the ACK and NACK services to inform the sender if the data has arrived
or not and checks for the integrity of data.

6. Flow Control
The transport layer provides a flow control mechanism between the
adjacent layers of the TCP/IP model. TCP also prevents data loss due to
a fast sender and slow receiver by imposing some flow control
techniques. It uses the method of sliding window protocol which is
accomplished by the receiver by sending a window back to the sender
informing the size of data it can receive.

Application Layer Protocols: The Web and http:

The application layer of the OSI and TCP/IP models is responsible for providing end-user services,
such as email, file transfer, and web browsing. One of the most widely used application layer
protocols is the HyperText Transfer Protocol (HTTP), which forms the foundation of the World Wide
Web (WWW).

1. The Web and its Components


The World Wide Web (WWW) is a system of interlinked documents and resources
accessed via the Internet. It enables users to navigate and retrieve content using web
browsers.
Key components of the web include:

 Web Browsers (e.g., Chrome, Firefox, Edge): Software that retrieves and renders
web pages.
 Web Servers (e.g., Apache, Nginx, IIS): Hosts websites and serves web content to
clients.
 Web Pages: Documents written in HTML (HyperText Markup Language), often
styled with CSS and made interactive with JavaScript.
 URLs (Uniform Resource Locators): Addresses used to access web resources (e.g.,
https://www.example.com).

HTTP stands for HyperText Transfer Protocol. It is the main way web
browsers and servers communicate to share information on the internet.
Tim Berner invents it. HyperText is the type of text that is specially coded
with the help of some standard coding language called HyperText
Markup Language (HTML). HTTP/2 is the new version of HTTP. HTTP/3
is the latest version of HTTP.

HTTP stands for “Hypertext Transfer Protocol.” It is a set of rules for


sharing data on the World Wide Web (WWW). HTTP helps web browsers
and servers communicate, allowing people to access and share
information over the internet.

 Basic Structure: HTTP forms the foundation of the web, enabling data
communication and file sharing.
 Web Browsing: Most websites use HTTP, so when you click on a link
or download a file, HTTP is at work.
 Client-Server Model: HTTP works on a request-response system.
Your browser (client) asks for information, and the website’s server
responds with the data.
 Application Layer Protocol: HTTP operates within the Internet
Protocol Suite, managing how data is transmitted and received.

The protocol used to transfer hypertext between two computers is known


as HyperText Transfer Protocol. HTTP provides a standard between a
web browser and a web server to establish communication. It is a set of
rules for transferring data from one computer to another. Data such as
text, images, and other multimedia files are shared on the World Wide
Web. Whenever a web user opens their web browser, the user indirectly
uses HTTP.

WORKING:
whenever we want to open any website we first open a web browser after
that we will type the URL of that website (e.g., www.facebook.com ). This
URL is now sent to the Domain Name Server (DNS). Then DNS first
checks records for this URL in their database, and then DNS will return
the IP address to the web browser corresponding to this URL. Now the
browser is able to send requests to the actual server.

After the server sends data to the client, the connection will be closed. If
we want something else from the server we should have to re-establish
the connection between the client and the server.

HTTP request is simply termed as the information or data that is needed


by Internet browsers for loading a website. This is simply known as HTTP
Request.

There is some common information that is generally present in all HTTP


requests. These are mentioned below.
 HTTP Version
 URL
 HTTP Method
 HTTP Request Headers
 HTTP Body

HTTP Request Headers


HTTP Request Headers generally store information in the form of key-
value and must be present in each HTTP Request. The use of this
Request Header is to provide core information about the client’s
information, etc.

HTTP Request Body


HTTP Request Body simply contains the information that has to be
transferred. HTTP Request has the information or data to be sent to these
browsers.

HTTP Method
HTTP Methods are simply HTTP Verb. In spite of being present so many
HTTP Methods, the most common HTTP Methods are HTTP GET and
HTTP POST. These two are generally used in HTTP cases. In HTTP
GET, the information is received in the form of a website.

HTTP Response:

HTTP Response is simply the answer to what a Server gets when the
request is raised. There are various things contained in HTTP Response,
some of them are listed below.
 HTTP Status Code
 HTTP Headers
 HTTP Body

HTTP Response Headers


HTTP Response headers are simply like an HTTP Request where it has
that work to send some important files and data to the HTTP Response
Body.
HTTP Response Body
HTTP Responses are the responses that are received successfully upon
the request. Generally, it comes under the requests generated by the
web. In most cases, the request is to transfer the HTML data into a
webpage.

HTTP Status Codes are the 3-digit codes that tell the message or simply
tell us about the HTTP Request whether it has been completed or not.
There are simply 5 types of status codes.

 Informational
 Successful
 Re-directional
 Client-Error
 Server-Error

Characteristics of HTTP

HTTP is IP based communication protocol that is used to deliver data


from server to client or vice-versa.
 The server processes a request, which is raised by the client, and also
server and client know each other only during the current bid and
response period.
 Any type of content can be exchanged as long as the server and client
are compatible with it.
 Once data is exchanged, servers and clients are no longer connected.
 It is a request and response protocol based on client and server
requirements.
 It is a connection-less protocol because after the connection is closed,
the server does not remember anything about the client and the client
does not remember anything about the server.

Cookies in HTTP
An HTTP cookie (web cookie, browser cookie) is a little piece of data that
a server transmits to a user’s web browser. When making subsequent
queries, the browser may keep the cookie and transmit it back to the
same server. An HTTP cookie is typically used, for example, to maintain a
user’s login state, and to determine whether two requests originate from
the same browser. For the stateless HTTP protocol, it retains stateful
information.

Advantages of HTTP
 Memory usage and CPU usage are low because of fewer simultaneous
connections.
 Since there are few TCP connections hence network congestion is
less.
 Since handshaking is done at the initial connection stage, then latency
is reduced because there is no further need for handshaking for
subsequent requests.
 The error can be reported without closing the connection.

 HTTP allows HTTP pipe-lining of requests or responses.


Persistent and Non-persistent connections:

In HTTP communication, connections between a client (browser) and a web server can be persistent
or non-persistent, depending on how they handle multiple requests and responses.

1. Non-Persistent Connections (HTTP/1.0)


In non-persistent HTTP, the connection between the client and the server is closed after
each request-response cycle. If the client needs additional resources (e.g., images, CSS files,
scripts), it must establish a new connection for each request.

How Non-Persistent Connections Work:

1. The client opens a new TCP connection to the server.


2. The client sends an HTTP request (e.g., for an HTML page).
3. The server processes the request and sends an HTTP response.
4. The server closes the connection after sending the response.
5. If more resources are needed, the client repeats steps 1–4 for each request.

Drawbacks of Non-Persistent Connections:

 High latency: Opening and closing a connection for every request increases delay.
 More overhead: Repeated TCP handshakes consume network and server resources.
 Slow page loading: A webpage with multiple elements (images, CSS, JS) requires
multiple connections.

Example:

A webpage contains 1 HTML file, 5 images, and 1 CSS file → Requires 7 separate
connections.

2. Persistent Connections (HTTP/1.1 and Later)


In persistent HTTP, the connection between the client and server remains open for multiple
requests and responses, reducing latency and improving efficiency.

How Persistent Connections Work:

1. The client opens a single TCP connection to the server.


2. The client sends an HTTP request.
3. The server processes and sends the response without closing the connection.
4. The client can send additional requests over the same connection.
5. The connection remains open until a timeout or explicit closure.

Advantages of Persistent Connections:

 Reduced latency: Fewer TCP handshakes improve speed.


 Less network congestion: Fewer connections reduce bandwidth usage.
 Efficient resource loading: Multiple elements of a webpage can be fetched over a
single connection.

Types of Persistent Connections:

1. Without Pipelining: The client sends a request, waits for the response, then sends the
next request.
2. With Pipelining (HTTP/1.1): The client sends multiple requests without waiting for
responses, improving performance. (However, HTTP/2 multiplexing has replaced
pipelining.)

Example:
A webpage contains 1 HTML file, 5 images, and 1 CSS file → Only 1 connection is
required to fetch all resources.

3. Persistent Connections in HTTP/2 and HTTP/3


 HTTP/2 introduced multiplexing, which allows multiple requests and responses to
be sent simultaneously over a single persistent connection.
 HTTP/3 uses QUIC instead of TCP, further reducing latency and improving
reliability.

http message format:

HTTP messages are the way clients (browsers) and servers communicate over the web. These
messages follow a structured format and are classified into two types:

1. HTTP Request Messages (sent by the client to request data from a server).
2. HTTP Response Messages (sent by the server to respond to a client's request).

1. HTTP Request Message Format


An HTTP request consists of:

 Request Line (includes method, resource, and HTTP version).


 Headers (metadata about the request).
 Optional Body (data sent with the request, mainly in POST and PUT).

Structure of an HTTP Request Message


vbnet
CopyEdit
METHOD REQUEST-URI HTTP-VERSION
Header1: value
Header2: value
...
(blank line)
Body (optional)

Example of an HTTP Request:


pgsql
CopyEdit
GET /index.html HTTP/1.1
Host: www.example.com
User-Agent: Mozilla/5.0
Accept: text/html
(blank line)
Explanation:

 GET → The HTTP method (request type).


 /index.html → The requested resource (webpage).
 HTTP/1.1 → The HTTP version.
 Host: www.example.com → Specifies the server to connect to.
 User-Agent: Mozilla/5.0 → Iden fies the browser making the request.
 Accept: text/html → Specifies the response content type the client can accept.
 (Blank line) → Separates headers from the body (no body in a GET request).

2. HTTP Response Message Format


An HTTP response consists of:

 Status Line (includes HTTP version, status code, and status message).
 Headers (metadata about the response).
 Optional Body (contains the requested resource or error message).

Structure of an HTTP Response Message


vbnet
CopyEdit
HTTP-VERSION STATUS-CODE STATUS-MESSAGE
Header1: value
Header2: value
...
(blank line)
Body (optional)

Example of an HTTP Response:


php-template
CopyEdit
HTTP/1.1 200 OK
Date: Fri, 14 Mar 2025 12:00:00 GMT
Server: Apache/2.4.41 (Ubuntu)
Content-Type: text/html
Content-Length: 1256
(blank line)
<html>
<body>
<h1>Welcome to Example.com</h1>
</body>
</html>

Explanation:

 HTTP/1.1 → The HTTP version used.


 200 OK → Status code indica ng success.
 Date: Fri, 14 Mar 2025 12:00:00 GMT → The date and me of the response.
 Server: Apache/2.4.41 (Ubuntu) → Server so ware informa on.
 Content-Type: text/html → Specifies that the response contains an HTML page.
 Content-Length: 1256 → The size of the response body in bytes.
 (Blank line) → Separates headers from the body.
 Body → Contains the actual web page content.

HTTP Status Codes in Response Messages


HTTP response messages include a status code that indicates the result of the request.
Common status codes:

 1xx (Informational): Request received, continuing process.


o 100 Continue – The request is being processed.
 2xx (Success): The request was successfully processed.
o 200 OK – The request succeeded.
o 201 Created – A new resource was created.
 3xx (Redirection): Further action is needed.
o 301 Moved Permanently – The resource has a new URL.
o 302 Found – Temporary redirection.
 4xx (Client Errors): The request has an error.
o 400 Bad Request – The request is malformed.
o 401 Unauthorized – Authentication is required.
o 403 Forbidden – Access denied.
o 404 Not Found – The resource does not exist.
 5xx (Server Errors): The server failed to process the request.
o 500 Internal Server Error – A generic server error.
o 503 Service Unavailable – The server is temporarily overloaded or down.

Differences Between Request and Response Messages


Feature HTTP Request HTTP Response

Starts
Request Line (GET / HTTP/1.1) Status Line (HTTP/1.1 200 OK)
With

Provides the requested resource or an error


Purpose Asks the server for a resource
message

Includes Host, User-Agent, Includes Server, Content-Type, Content-


Headers
Accept, etc. Length, etc.

Optional (mainly used in POST and


Body Optional (contains the resource if applicable)
PUT)
Proxy server:

A proxy server is an intermediary between a client (e.g., a web browser) and a destination server.
Instead of connecting directly to a website, a client sends its request to the proxy server, which then
forwards the request to the website on behalf of the client. The website's response is also routed
through the proxy before reaching the client.

Types of Proxy Servers:

1. Forward Proxy:
o Used by clients to access external networks (e.g., the internet).
o Common in businesses and schools to filter, monitor, and control internet
access.
2. Reverse Proxy:
o Used by web servers to handle requests from clients.
o Protects web servers, improves performance, and enables load balancing.
3. Transparent Proxy:
o Does not modify requests and responses.
o Users may not even be aware they are using a proxy.
4. Anonymous Proxy:
o Hides the client’s IP address to enhance privacy.
5. Caching Proxy:
o Stores copies of frequently accessed web pages to reduce load times and
bandwidth usage.
6. VPN Proxy:
o Encrypts internet traffic and masks the user’s real IP address.

Advantages of Proxy Servers:

 Improved Security: Protects internal networks by acting as a firewall.


 Anonymity & Privacy: Hides users’ IP addresses.
 Content Filtering: Blocks access to restricted or harmful websites.
 Caching & Performance: Speeds up browsing by storing frequently accessed
resources.
 Load Balancing: Distributes traffic across multiple servers to prevent overload.

Disadvantages of Proxy Servers:

 Potential Privacy Risks: Some proxies log user data.


 Speed Issues: May slow down browsing if overloaded.
 Security Concerns: Free proxies may inject ads or malware.

Cookies:

Cookies are small text files stored on a user's browser by a website. They contain data about
the user’s activity, preferences, and session information to enhance the browsing experience.
Types of Cookies:

1. Session Cookies:
o Temporary cookies that expire when the browser is closed.
o Used for login sessions and shopping carts.
2. Persistent Cookies:
o Stored on the user's device for a set period.
o Used for remembering preferences, login details, and tracking behavior.
3. First-Party Cookies:
o Set by the website being visited.
o Used for user authentication and site preferences.
4. Third-Party Cookies:
o Set by external websites (e.g., advertisers and analytics services).
o Used for tracking users across multiple sites for targeted ads.
5. Secure Cookies:
o Sent only over HTTPS to prevent data theft.
6. HTTP-Only Cookies:
o Cannot be accessed by JavaScript, reducing the risk of cross-site scripting
(XSS) attacks.

How Cookies Work:

1. A user visits a website.


2. The website’s server sends a cookie to the browser.
3. The browser stores the cookie.
4. On future visits, the browser sends the cookie back to the server, allowing the website
to remember user preferences.

Uses of Cookies:

 User Authentication: Keeps users logged in.


 Personalization: Stores preferences (e.g., language settings, themes).
 Shopping Carts: Maintains items in carts across sessions.
 Analytics & Tracking: Helps websites understand user behavior.
 Advertising: Enables targeted ads based on browsing history.

Privacy Concerns with Cookies:

 Tracking & Profiling: Advertisers can track users across websites.


 Security Risks: Unencrypted cookies can be intercepted (cookie hijacking).
 Third-Party Exploitation: Some websites share cookie data with advertisers without
user consent.

How to Manage Cookies:

 Delete Cookies: Clear browser history regularly.


 Disable Third-Party Cookies: Adjust browser settings to block tracking cookies.
 Use Private Browsing Mode: Prevents cookies from being stored after the session
ends.
 Use Browser Extensions: Tools like ad blockers prevent tracking.

Comparison: Proxy Server vs. Cookies


Feature Proxy Server Cookies
Hides IP address, filters content, Stores user preferences, authentication,
Purpose
improves security and tracking data
Location Resides between client and server Stored in the client’s browser
Increases privacy by hiding user
Privacy Impact Can track and profile users
identity
Performance Can slow or speed up browsing Can slow browsing if excessive
Impact (caching proxies) cookies are stored
Some proxies may log data or Can be exploited for tracking and
Security Risks
inject ads session hijacking

conditional GET:

A Conditional GET is an HTTP request that asks the server only to send a resource if it has been
modified since the last time the client accessed it. This helps reduce bandwidth usage and improve
performance by avoiding unnecessary data transfers.

Use of Conditional GET:

 Reduces network traffic by preventing redundant data transfers.


 Improves load time since unchanged resources are not reloaded.
 Optimizes caching by allowing browsers and proxy servers to store resources efficiently.

Working:

A Conditional GET request includes specific header fields that instruct the server to check whether
the resource has changed before sending a response.

HTTP Headers Used in Conditional GET

1. If-Modified-Since
o Asks the server to send the resource only if it has been modified since the
given date.
o If unchanged, the server responds with 304 Not Modified instead of sending
the resource again.

Example Request:

yaml
CopyEdit
GET /image.jpg HTTP/1.1
Host: www.example.com
If-Modified-Since: Tue, 12 Mar 2024 10:30:00 GMT

Possible Server Response (if unchanged):

mathematica
CopyEdit
HTTP/1.1 304 Not Modified

Possible Server Response (if modified):

arduino
CopyEdit
HTTP/1.1 200 OK
Content-Type: image/jpeg
Content-Length: 45231
(Binary image data...)

2. If-Unmodified-Since
o Opposite of If-Modified-Since.
o The server sends the resource only if it has NOT been modified since the
given date.
o If the resource has been modified, the server responds with 412 Precondition
Failed.
3. If-None-Match (ETag-based Validation)
o Uses an ETag (Entity Tag), a unique identifier for the resource, instead of a
timestamp.
o The server only sends the resource if the ETag has changed.

Example Request:

sql
CopyEdit
GET /style.css HTTP/1.1
Host: www.example.com
If-None-Match: "abc123etag"

Server Response (if unchanged):

mathematica
CopyEdit
HTTP/1.1 304 Not Modified

Server Response (if modified):

yaml
CopyEdit
HTTP/1.1 200 OK
ETag: "xyz456etag"
Content-Type: text/css
Content-Length: 1024
(CSS file data...)
Conditional GET and Caching
 Web browsers use Conditional GET to check if cached resources are still valid.
 If unchanged, the browser reuses the cached version, saving bandwidth and
improving page load speed.
 Conditional GET is commonly used for static assets like images, stylesheets, and
JavaScript files.

Summary of Response Codes


Status Code Meaning
200 OK The resource has changed; the server sends the new content.
The resource has not changed; the client should use its cached
304 Not Modified
version.
412 Precondition The condition in the request (e.g., If-Unmodified-Since) was not
Failed met.

File Transfer Protocol:

The File Transfer Protocol (FTP) is a standard network protocol used to transfer files between a
client and a server over a TCP-based network, such as the internet. FTP is one of the oldest
protocols, designed to facilitate the upload, download, and management of files on remote servers.

FTP operates using a client-server architecture, where:

1. The FTP client (user’s computer) initiates a connection to an FTP server.


2. The client authenticates using a username and password (or connects anonymously).
3. The client can upload, download, delete, or list files on the server.

Ports Used in FTP:

 Port 21: Used for control commands (e.g., authentication, navigation).


 Port 20: Used for data transfer (file upload/download).

Modes of FTP Operation


a) Active Mode FTP

 The client connects to the server on port 21 (control connection).


 The server initiates a data connection back to the client on a random port (data
connection).
 Firewall Issues: Since the server initiates the data connection, firewalls may block it.

b) Passive Mode FTP (Recommended for Firewalls/NAT)

 The client connects to the server on port 21 (control connection).


 Instead of the server initiating the data connection, the client requests a passive
mode connection.
 The server provides a random port number, and the client connects to that port.
 Firewall-Friendly: Since the client initiates both connections, passive mode is
preferred for security.

Types of FTP Connections


a) Anonymous FTP

 Allows users to connect without authentication (no username/password).


 Commonly used for public file repositories (e.g., software downloads).

b) Authenticated FTP

 Requires a valid username and password to access the server.


 Used in private file-sharing and enterprise environments.

c) Secure FTP Variants

FTP is not encrypted by default, making it vulnerable to attacks. Secure alternatives include:

1. FTPS (FTP Secure): Adds SSL/TLS encryption to protect data.


2. SFTP (SSH File Transfer Protocol): Uses SSH encryption, providing better
security.

FTP Commands
FTP uses text-based commands to communicate. Some common commands include:

Command Description
USER username Logs in with a username.
PASS password Logs in with a password.
LIST Lists files in a directory.
RETR filename Downloads a file.
STOR filename Uploads a file.
DELE filename Deletes a file.
CWD directory Changes the working directory.
Command Description
QUIT Closes the connection.

Advantages of FTP
✅Efficient for bulk file transfers
✅Supports resume and scheduling
✅Widely supported across platforms
✅Can be automated using scripts

Disadvantages of FTP
❌Lack of security (unencrypted data in basic FTP)
❌Requires manual configuration for firewall/NAT traversal
❌Not optimized for modern web-based file sharing

SMTP AND POP3

SMTP is a protocol used to send emails from a client (e.g., an email app) to a mail server or between
mail servers. It is responsible for email transmission but not for receiving emails.

SMTP WORKING:

1. The user composes an email in an email client (e.g., Outlook, Gmail).


2. The email client sends the email to the SMTP server.
3. The SMTP server looks up the recipient's mail server using DNS (MX records).
4. The SMTP server forwards the email to the recipient’s mail server.
5. The recipient’s mail server stores the email until retrieved using POP3 or IMAP.

SMTP Ports

Port Usage
25 Standard SMTP (mostly for server-to-server communication)
587 SMTP with encryption (STARTTLS) – Recommended for sending emails
465 SMTP with SSL encryption (deprecated, but still used by some services)

SMTP Commands

SMTP uses text-based commands for email transmission. Some common ones include:

Command Description
HELO / EHLO Identifies the client to the server
MAIL FROM: Specifies the sender’s email address
Command Description
RCPT TO: Specifies the recipient’s email address
DATA Starts the message body
QUIT Ends the session

Advantages of SMTP

✅Reliable for email transmission


✅Supports multiple recipients (CC, BCC)
✅Works with encryption for security (TLS, SSL)

Disadvantages of SMTP

❌Not designed for receiving emails


❌Plain SMTP (without encryption) is insecure

POP3 (Post Office Protocol v3):

POP3 is a protocol used by email clients to retrieve emails from a mail server. It downloads emails
to the user’s device and, by default, deletes them from the server.

Working:

1. The email client connects to the mail server using POP3.


2. The server authenticates the user (username & password).
3. The client downloads all new emails from the server.
4. The emails are deleted from the server (unless configured otherwise).

POP3 Ports

Port Usage
110 Standard POP3 (unencrypted)
995 POP3 with SSL/TLS encryption (recommended)

POP3 Commands

Command Description
USER Provides the username
PASS Provides the password
LIST Lists all emails on the server
RETR Retrieves an email
DELE Deletes an email
QUIT Closes the session

Advantages of POP3
✅Works offline (emails stored on the device)
✅Faster access once emails are downloaded
✅Reduces server storage use

Disadvantages of POP3

❌Emails are deleted from the server (unless set to keep a copy)
❌Emails can’t be accessed from multiple devices easily
❌If the device crashes, emails may be lost

3. SMTP vs. POP3: Key Differences


Feature SMTP POP3
Purpose Sending emails Retrieving emails
Works with Email clients & servers Email clients
Ports 25, 587, 465 110, 995
No storage, just
Email Storage Downloads emails to a device
forwarding
Access from Multiple Difficult (since emails are removed from
Not applicable
Devices the server)

IMAP, MIME

IMAP is a protocol used for retrieving emails from a mail server. Unlike POP3, IMAP keeps emails
stored on the server, allowing users to access their email from multiple devices (e.g., phone, laptop,
tablet).

WORKING:

1. The email client connects to the mail server using IMAP.


2. The server stores all emails, and the client syncs with the server.
3. Users can read, delete, and organize emails without downloading them permanently.
4. Changes made on one device (e.g., marking an email as read) are reflected on all
devices.

IMAP Ports

Port Usage
143 Standard IMAP (unencrypted)
993 IMAP with SSL/TLS encryption (recommended)

IMAP Commands

Command Description
Command Description
LOGIN Authenticates the user
LIST Lists available mailboxes
SELECT Selects a mailbox to access
FETCH Retrieves emails
STORE Updates email flags (e.g., read/unread)
LOGOUT Closes the session

Advantages of IMAP

✅Access emails from multiple devices


✅Emails remain on the server (backup and sync)
✅Faster, as only headers are downloaded initially
✅Organize emails into folders on the server

Disadvantages of IMAP

❌Requires internet connection to view full emails


❌Uses more server storage
❌Slightly more complex than POP3

MIME is an extension of SMTP that allows emails to include multimedia content, such as:

 Attachments (PDFs, images, videos)


 HTML-formatted emails
 Multiple text encodings (e.g., Unicode, different character sets)

How MIME Works

1. When a user sends an email with attachments or formatted text, MIME encodes the
content.
2. The email is transmitted as plain text with special MIME headers describing the
format.
3. The recipient’s email client decodes the MIME message and displays it properly.

MIME Headers

Header Description
Content-Type Defines the type of content (e.g., text/html, image/png)
Content-Transfer- Specifies how the content is encoded (e.g., Base64 for
Encoding attachments)
Content-Disposition Suggests how to display the file (inline or attachment)
MIME-Version Indicates the email supports MIME (e.g., 1.0)
Example MIME Email with an Attachment
bash
CopyEdit
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="boundary123"

--boundary123
Content-Type: text/plain

Hello, this is a test email with an attachment.

--boundary123
Content-Type: image/png
Content-Transfer-Encoding: base64
Content-Disposition: attachment; filename="image.png"

(iVBORw0KGgoAAAANSUhEUgAAA...)
--boundary123--

Here, the text/plain part contains the email body, and the image/png part contains an
attachment encoded in Base64.

DOMAIN NAME SYSTEM

DNS (Domain Name System) is a decentralized system that translates human-readable domain
names (e.g., www.example.com) into IP addresses (e.g., 192.168.1.1). Since computers
communicate using IP addresses, DNS allows users to access websites using easy-to-remember
names instead of numerical addresses.

Services Provided by DNS


a) Name Resolution (Domain to IP Translation)

DNS converts domain names into IP addresses so that browsers can load websites.

Example:

 You type www.google.com in your browser.


 DNS resolves it to 142.250.190.46 (Google’s server IP).
 Your browser connects to this IP address to load the website.

b) Load Balancing

 Large websites use multiple servers to handle traffic.


 DNS directs users to the closest or least busy server using techniques like Round
Robin DNS.

c) Email Routing (MX Records)


 DNS helps route emails by specifying which mail servers handle email for a domain.
 Example: The MX (Mail Exchange) Record for gmail.com tells mail servers where
to send emails for Gmail users.

d) Caching for Faster Access

 DNS servers cache previously resolved queries to reduce response times and improve
efficiency.
 Example: If you visit www.amazon.com, your local DNS resolver stores the IP for
faster future access.

e) Reverse DNS Lookup (IP to Domain Name)

 Used for security checks and email verification.


 Converts an IP address back into a domain name (opposite of normal DNS
resolution).

f) Security Features (DNSSEC, Filtering)

 DNSSEC (DNS Security Extensions): Protects against DNS spoofing attacks.


 Content Filtering: Some DNS providers block malicious websites (e.g., Google Safe
Browsing, OpenDNS).

How DNS Works (Step-by-Step Process)


Step 1: User Requests a Website

 You type www.example.com in your web browser.


 Your computer checks its local cache for the IP address.
 If not found, it queries the DNS resolver.

Step 2: Query to DNS Resolver (ISP’s DNS Server)

 The request goes to your Internet Service Provider’s (ISP) DNS resolver.
 If the ISP has the record cached, it returns the IP.
 If not, the ISP forwards the request to root DNS servers.

Step 3: Query to Root DNS Servers

 Root servers don’t know the exact IP but direct the request to a Top-Level Domain
(TLD) server (e.g., .com server).

Step 4: Query to TLD Server

 The TLD server (e.g., .com server) directs the request to the Authoritative Name
Server for example.com.

Step 5: Query to Authoritative Name Server


 The Authoritative Name Server for example.com provides the IP address (e.g.,
192.168.1.100).

Step 6: Website Loads

 The DNS resolver sends the IP address back to your computer.


 Your browser connects to the IP and loads the website.

Types of DNS Servers


Server Type Function

Queries other DNS servers on behalf of the client (e.g., ISP's DNS
Recursive Resolver
server).

Root DNS Server Directs queries to TLD servers (e.g., .com, .org).

TLD (Top-Level Domain)


Directs queries to the correct authoritative name server.
Server

Authoritative Name Server Provides the final IP address for the domain.

Types of DNS Records


Record Type Purpose

A Record Maps a domain to an IPv4 address.

AAAA Record Maps a domain to an IPv6 address.

CNAME Record Creates an alias for a domain (e.g., www.example.com → example.com ).

MX Record Specifies mail servers for email delivery.

NS Record Specifies the authoritative name server for a domain.

PTR Record Performs Reverse DNS lookup (IP to domain name).

TXT Record Stores text data for domain verification, security (e.g., SPF, DKIM).

DNS Caching & Performance


 Local Cache: Your device stores recent DNS lookups.
 ISP DNS Cache: Your ISP’s DNS resolver caches records for fast responses.
 Browser Cache: Web browsers also store DNS queries for speed.
 TTL (Time to Live): Defines how long a DNS record remains cached (e.g., 300
seconds).

DNS Security Issues & Solutions


Threat Description Solution

Fake DNS responses redirect users to


DNS Spoofing Use DNSSEC for verification.
malicious sites.

Use Anycast Routing & Cloud DNS


DDoS Attacks Hackers overload DNS servers.
providers.

Man-in-the-Middle
Attackers modify DNS responses. Use Encrypted DNS (DoH, DoT).
Attacks

DoH (DNS over HTTPS): Encrypts DNS traffic via HTTPS.


DoT (DNS over TLS): Encrypts DNS traffic via TLS for privacy.

Popular DNS Providers


Provider Features

Google DNS (8.8.8.8) Fast, free, and secure.

Cloudflare DNS (1.1.1.1) Privacy-focused, very fast.

OpenDNS (208.67.222.222) Security & parental controls.

Quad9 (9.9.9.9) Blocks malicious domains.

DNS MESSAGE

DNS messages are used to resolve domain names into IP addresses. The DNS protocol follows a
client-server model, where a DNS client (resolver) sends a query, and a DNS server responds with a
DNS response.

There are two main types of DNS messages:

1. DNS Query Message – Sent by the client (resolver) requesting information.


2. DNS Response Message – Sent by the server with the requested information or an
error.

Both messages share the same format, consisting of five sections.


A DNS message consists of the following sections:

Section Description
Header Contains general information about the query/response.
Question Specifies the domain name being queried.
Answer Contains the response (IP address or other record).
Authority Specifies authoritative name servers.
Additional Provides extra information (e.g., caching details).

DNS Message Structure (Packet Format)


(a) DNS Header (First 12 Bytes, Common for Queries & Responses)

Field Size Description

Transaction ID 16 bits A unique identifier for the request.

Flags 16 bits Specifies query type, response code, and recursion.

Question Count (QDCOUNT) 16 bits Number of queries in the Question section.

Answer Count (ANCOUNT) 16 bits Number of answers in the Answer section.

Authority Count (NSCOUNT) 16 bits Number of authority records.

Additional Count (ARCOUNT) 16 bits Number of additional records.

Flags Field (16 bits) Breakdown:

Bit(s) Field Description

0 Query (0) / Response (1) Indicates whether it's a query or a response.

1-4 Opcode Defines the query type (0 = standard query).

5 AA (Authoritative Answer) 1 if the response is from an authoritative server.

6 TC (Truncated) 1 if the message is too long and truncated.

7 RD (Recursion Desired) 1 if recursion is requested.

8 RA (Recursion Available) 1 if the server supports recursion.

9-15 RCODE Response code (0 = No Error, 3 = Name Error, etc.).


(b) Question Section (Client Request)

Field Description
QNAME Domain name being queried (e.g., www.google.com).
QTYPE Type of record requested (A, MX, CNAME, etc.).
QCLASS Typically IN for Internet.

Example:
If a client wants the IP of www.example.com, the Question section will contain:

 QNAME: www.example.com
 QTYPE: A (IPv4 address request)
 QCLASS: IN (Internet class)

(c) Answer Section (Server Response)

Contains the resolved IP address or requested record.

Field Description
NAME Domain name being answered.
TYPE Record type (A, AAAA, MX, etc.).
CLASS Typically IN for Internet.
TTL Time-to-Live (how long to cache the response).
RDLENGTH Length of response data.
RDATA The actual response (e.g., an IP address).

Example Answer:

 NAME: www.example.com
 TYPE: A
 TTL: 300
 RDATA: 192.168.1.100

Authority Section (Authoritative Name Server Info)

This section provides the name servers responsible for the domain.

Field Description

NAME Domain name.

TYPE Record type (e.g., NS for Name Server).

RDATA Name of authoritative DNS server.


Example:
If no direct answer is found, the server may return:

 NAME: example.com
 TYPE: NS
 RDATA: ns1.example.com (authoritative server for example.com).

Additional Section (Extra Information for Processing)

This section contains additional helpful information, like IP addresses of name servers.

Example:

 NAME: ns1.example.com
 TYPE: A
 RDATA: 192.168.2.1 (IP address of the authoritative name server).

(a) DNS Query Example (Client Requesting www.google.com)


yaml
CopyEdit
Header:
Transaction ID: 1234
Flags: 0x0100 (Standard Query, Recursion Desired)
Questions: 1

Question Section:
QNAME: www.google.com
QTYPE: A
QCLASS: IN

(b) DNS Response Example (Server Replying with IP Address)


yaml
CopyEdit
Header:
Transaction ID: 1234
Flags: 0x8180 (Response, No Error)
Questions: 1
Answers: 1

Answer Section:
NAME: www.google.com
TYPE: A
TTL: 300
RDATA: 142.250.190.46

Now, the client’s browser connects to 142.250.190.46 to load Google's website.

DNS Query Types


Query Type Description
Query Type Description

Recursive Query The DNS resolver finds the answer and returns it to the client.

Iterative Query The DNS resolver refers the client to another DNS server.

Inverse Query Resolves an IP address to a domain name (Reverse DNS lookup).

Common DNS Response Codes (RCODE Field in Header)


RCODE Meaning Description

0 No Error Successful response.

1 Format Error Badly formatted query.

2 Server Failure DNS server issue.

3 Name Error Domain name not found (NXDOMAIN).

4 Not Implemented Query type not supported.

5 Refused Server refuses to process the query.

introduction to p2p file distribution: BitTorrent

Peer-to-Peer (P2P) file distribution is a method of sharing files where each participant
(peer) acts as both a client and a server. Unlike traditional client-server models, P2P
networks distribute the workload among multiple peers, making file transfers faster,
scalable, and more efficient.

Advantages of P2P File Distribution

✅Scalability – More peers = faster downloads.


✅Efficient Bandwidth Use – Reduces server load.
✅Resilience – No single point of failure.
✅Faster Speeds – Simultaneous downloading from multiple sources.

BitTorrent is one of the most popular P2P file-sharing protocols designed for efficient large-scale file
distribution. Instead of downloading a file from a single server, BitTorrent allows users to download
different parts of a file from multiple peers simultaneously, making it faster and more reliable.

How BitTorrent Works


Step 1: The Torrent File (.torrent)

 To share a file using BitTorrent, the uploader (seeder) creates a torrent file.
 This small file contains metadata about the shared file, including:
o File name and size
o Hash values for integrity verification
o Tracker URL (helps peers find each other)

Step 2: Connecting to the Tracker

 The torrent file is loaded into a BitTorrent client (e.g., uTorrent, qBittorrent).
 The client contacts a tracker (a central server) to find other peers sharing the same
file.

Step 3: Downloading Pieces from Peers

 Instead of downloading the file sequentially, BitTorrent splits it into small chunks
(pieces).
 The client downloads different chunks from multiple peers simultaneously.
 Once a peer downloads a chunk, it uploads (seeds) it to others.

Step 4: Sharing (Seeding) After Download Completion

 After downloading the entire file, a user can continue sharing (seeding) with others.
 The more seeders a file has, the faster the download speeds for new peers.

Components of BitTorrent
Term Description

Seeder A peer that has 100% of the file and shares it with others.

Leecher A peer that is downloading the file but hasn’t finished yet.

Swarm The group of peers (seeders + leechers) sharing a file.

Tracker A server that helps peers find each other.

Piece A small chunk of a file (e.g., 256 KB or 1 MB).

Magnet Link A URL-style alternative to torrent files that contains hash info to find peers.

Advantages of BitTorrent Over Traditional File


Distribution
Feature Traditional Client-Server BitTorrent P2P

Download Speed Slows down with more users Increases with more users

Server Load Centralized, high load Distributed, lower load

Fault Tolerance Server failure = no downloads Works even if some peers go offline

Bandwidth Efficiency Consumes high server bandwidth Uses multiple peers’ bandwidth

BitTorrent Protocol Optimizations


a) Piece Selection Strategy

 Rarest First – Prioritizes least available pieces to prevent bottlenecks.


 Random Selection – Helps avoid congestion on frequently requested pieces.

b) Choking & Unchoking (Peer Prioritization)

 Clients prioritize peers who share more data ("tit-for-tat" strategy).


 Active peers get faster speeds, discouraging "leeching" (downloading without
sharing).

c) Distributed Hash Table (DHT) for Trackerless Torrents

 DHT allows peers to find each other without a central tracker.


 Helps improve decentralization and reliability.

You might also like