Network Protocols - CSU359 - Shoolini University

Network Protocols

0. Network Protocols

Network protocols are formal rules that define how data is transmitted and received across a network. They ensure communication between devices by providing standards for data formats, addressing, transmission methods, and error handling. Protocols operate at different layers of the OSI (Open Systems Interconnection) or TCP/IP models, enabling devices to communicate, share resources, and ensure data integrity and security.

0.1 Types of Network Protocols

Network protocols are categorized based on their functions and the layers they operate in. Some common types include:

0.2 Routing Protocols

Routing protocols are used to determine the most efficient path for data to travel across interconnected networks. They operate on the Network Layer and are classified into two main types:

0.2.1 Distance Vector Protocols

These protocols calculate the best path based on the distance (or "cost") to the destination. Each router sends information about the networks it can reach to its immediate neighbors. Examples include:

0.2.2 Link State Protocols

Link state protocols build a complete map of the network and calculate the shortest path using algorithms like Dijkstra's Algorithm. Examples include:

0.3 Security Protocols

Security protocols are designed to protect the integrity, confidentiality, and authenticity of data transmitted across networks. Key protocols include:

0.3.1 IPsec (Internet Protocol Security)

IPsec is a suite of protocols used to secure IP communications by authenticating and encrypting each packet. It operates in two modes:

0.3.2 SSL/TLS (Secure Sockets Layer/Transport Layer Security)

SSL and its successor TLS provide encryption and authentication for data transmitted over networks, typically used to secure web traffic (HTTPS) and email (FTPS).

0.3.3 Kerberos

A network authentication protocol that uses secret-key cryptography to verify the identity of users and devices. Commonly used in enterprise environments.

0.4 Address Resolution Protocols

Address resolution protocols map network addresses (IP addresses) to physical hardware addresses (MAC addresses). Examples include:

0.4.1 ARP (Address Resolution Protocol)

ARP is used to resolve an IP address into a MAC address. When a device wants to communicate with another device on the same local network, it uses ARP to discover the MAC address of the destination.

0.4.2 RARP (Reverse Address Resolution Protocol)

RARP allows a device to request its own IP address from a server based on its MAC address. This protocol is used by devices that do not have any knowledge of their IP address when booting.

0.5 Session Control Protocols

Session control protocols manage the establishment, maintenance, and termination of communication sessions between devices. These protocols ensure data can be sent reliably and in sequence.

0.5.1 SIP (Session Initiation Protocol)

SIP is used for initiating, maintaining, and terminating real-time sessions that involve video, voice, messaging, and other communications over IP networks. Commonly used in VoIP (Voice over IP) and video conferencing applications.

0.5.2 L2TP (Layer 2 Tunneling Protocol)

L2TP is used to tunnel data between two network endpoints over the internet. It is often combined with IPsec to provide secure communication channels, especially in VPNs (Virtual Private Networks).

0.6 Network Time Protocol (NTP)

NTP is a protocol used to synchronize the clocks of devices across a network. It ensures that all systems have the same time, which is critical for time-sensitive operations like logging events and securing communications.

0.7 Dynamic Host Configuration Protocol (DHCP)

DHCP is a protocol used to automatically assign IP addresses and other network configuration settings (such as subnet mask, gateway, and DNS servers) to devices on a network. This ensures that devices can communicate without manual configuration.

0.8 DNS (Domain Name System)

DNS is a hierarchical protocol used to translate human-readable domain names (e.g., www.example.com) into IP addresses (e.g., 192.168.1.1). DNS enables users to access websites without remembering numerical IP addresses.

0.8.1 DNS Resolution Process

When a user types a domain name in a browser, the DNS resolver on the user's device queries DNS servers to find the corresponding IP address. The process involves multiple steps:

1. Network Protocols - Transmission Control Protocol/Internet Protocol (TCP/IP)

TCP/IP is the foundational suite of communication protocols used in the Internet and similar networks. It defines how data should be packetized, addressed, transmitted, routed, and received. TCP/IP has two primary protocols: Transmission Control Protocol (TCP) and Internet Protocol (IP). Together, they ensure reliable, organized communication across networked systems.

1.1 TCP/IP Model Layers

The TCP/IP model is structured in four layers, each responsible for a different aspect of communication:

1.2 Transmission Control Protocol (TCP)

TCP is a reliable, connection-oriented protocol that ensures data is transmitted accurately and in order. It establishes a connection before data transfer, breaks data into segments, and guarantees delivery using acknowledgment and retransmission techniques.

1.2.1 Key Features of TCP

# Three-Way Handshake Process
1. SYN: Client sends a SYN (synchronize) packet to initiate the connection.
2. SYN-ACK: Server responds with a SYN-ACK packet to acknowledge the request.
3. ACK: Client sends an ACK (acknowledgment) packet, and the connection is established.

1.3 Internet Protocol (IP)

IP is a connectionless protocol responsible for delivering packets from source to destination based on IP addresses. It works on the Internet Layer and does not guarantee delivery or packet ordering.

1.3.1 Types of IP
1.3.2 Packet Structure

Each IP packet contains a header and a payload:


# IPv4 Packet Structure
Version | Header Length | Type of Service | Total Length
Identification | Flags | Fragment Offset
Time to Live (TTL) | Protocol | Header Checksum
Source IP Address
Destination IP Address
Options (optional) | Padding
Data (payload)

1.4 User Datagram Protocol (UDP)

UDP is a simpler, connectionless alternative to TCP. It is faster but offers no guarantee of data delivery, ordering, or error checking. It is used for applications where speed is more important than reliability, like streaming or gaming.

1.4.1 Key Features of UDP

# UDP Packet Structure
Source Port | Destination Port
Length | Checksum
Data (payload)

1.5 IP Addressing and Subnetting

IP addressing is crucial for identifying devices in a network. A subnet mask is used to divide IP addresses into network and host portions, enabling efficient network design and management.

1.5.1 Subnet Mask

A subnet mask helps to determine the network and host parts of an IP address. It is typically written in dotted decimal form (e.g., 255.255.255.0).

1.5.2 Subnetting Example

IP Address: 192.168.1.10
Subnet Mask: 255.255.255.0

# Network address: 192.168.1.0
# Host range: 192.168.1.1 - 192.168.1.254
# Broadcast address: 192.168.1.255

1.6 Routing in TCP/IP Networks

Routing involves determining the optimal path for data to travel from source to destination across interconnected networks. Routers make decisions based on routing tables and protocols such as RIP, OSPF, and BGP.

1.6.1 Routing Table

Routers use routing tables to store information about possible network paths. A routing table typically includes:


# Sample Routing Table
Destination | Gateway | Genmask       | Flags | Metric | Interface
0.0.0.0     | 192.168.1.1 | 0.0.0.0       | UG    | 100    | eth0
192.168.1.0 | 0.0.0.0     | 255.255.255.0 | U     | 0      | eth0

2. User Datagram Protocol (UDP)

UDP is a core protocol in the Internet Protocol (IP) suite, used to send messages called datagrams between devices on an IP network. It is a connectionless protocol, meaning that it does not establish a connection before data transmission, nor does it ensure reliable delivery or order of the data. UDP is ideal for applications where speed is prioritized over reliability, such as real-time video streaming, online gaming, or voice over IP (VoIP).

2.1 Key Characteristics of UDP

2.2 UDP Packet Structure

Each UDP packet consists of a header and a data section (payload). The UDP header is simpler than the TCP header, containing only 4 fields:


# UDP Packet Structure
Source Port | Destination Port
Length      | Checksum
Data (payload)

2.3 Advantages of Using UDP

2.4 Use Cases for UDP

UDP is commonly used in scenarios where timely delivery of data is more critical than ensuring accuracy. Examples include:

2.5 Differences Between TCP and UDP

TCP and UDP serve different purposes, and understanding their differences helps choose the appropriate protocol for a given application:

Feature TCP UDP
Connection Type Connection-oriented (requires a connection setup) Connectionless (no connection required)
Reliability Reliable, with acknowledgment, retransmission, and error checking Unreliable, no acknowledgment, no retransmission
Ordering Ensures data arrives in order No guarantee of order
Speed Slower due to overhead Faster with less overhead
Use Cases File transfer, email, web browsing Video streaming, online gaming, VoIP

2.6 Example of UDP in Code

Here is a basic example of how UDP can be implemented in Python using socket programming:


import socket

# UDP Server
server_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
server_socket.bind(('localhost', 12345))
print("Server listening...")

while True:
    data, addr = server_socket.recvfrom(1024)
    print(f"Received message: {data.decode()} from {addr}")
    server_socket.sendto(b"Message received", addr)

# UDP Client
client_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
client_socket.sendto(b"Hello UDP Server", ('localhost', 12345))
message, server = client_socket.recvfrom(1024)
print(f"Received reply from server: {message.decode()}")
client_socket.close()

This code sets up a basic UDP server and client. The server listens on a port for incoming datagrams, while the client sends a message to the server. Notice that no connection is established, and the data is sent and received without acknowledgment.

3. Hypertext Transfer Protocol (HTTP/HTTPS)

HTTP (Hypertext Transfer Protocol) and HTTPS (HTTP Secure) are the primary protocols used for transmitting data over the web. HTTP is a stateless, application-layer protocol designed to facilitate communication between web browsers (clients) and web servers. HTTPS is the secure version of HTTP, which adds encryption to ensure the confidentiality and integrity of data being transmitted.

3.1 Key Characteristics of HTTP

3.2 Key Characteristics of HTTPS

3.3 HTTP Request and Response Structure

HTTP operates using a request-response structure:

3.3.1 HTTP Request

An HTTP request consists of:


GET /index.html HTTP/1.1
Host: dmj.one
User-Agent: Mozilla/5.0
3.3.2 HTTP Response

An HTTP response consists of:


HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 138
Server: Apache/2.4.1

<html>
  <body>
    <h1>Welcome to the Homepage
  </body>
</html>

3.4 Status Codes in HTTP

Status codes are used to indicate the result of an HTTP request. These codes are grouped into five categories:

3.5 SSL/TLS in HTTPS

HTTPS employs SSL (Secure Sockets Layer) or TLS (Transport Layer Security) to encrypt the connection between the client and server. This encryption ensures that sensitive information, such as passwords or payment details, remains secure during transmission.

3.5.1 SSL/TLS Handshake

The SSL/TLS handshake is a process that establishes a secure connection between a client and a server:


# Simplified TLS Handshake
1. Client Hello -> Server Hello
2. Server sends certificate
3. Client verifies certificate
4. Key exchange
5. Secure data transmission

3.6 Advantages of HTTPS Over HTTP

3.7 Example of HTTP and HTTPS Communication

Below is a Python example using the requests library to demonstrate HTTP and HTTPS requests:


import requests

# HTTP Request (Insecure)
response_http = requests.get('http://dmj.one')
print("HTTP Response:", response_http.status_code)

# HTTPS Request (Secure)
response_https = requests.get('https://dmj.one')
print("HTTPS Response:", response_https.status_code)

In this example, the same URL is accessed using both HTTP and HTTPS. The HTTPS request provides an encrypted, secure connection, while the HTTP request does not.

4. Simple Mail Transfer Protocol (SMTP)

Simple Mail Transfer Protocol (SMTP) is a protocol used for sending emails across the Internet. It operates on the application layer and facilitates communication between email servers to ensure the reliable transfer of email messages. SMTP is primarily responsible for pushing messages from the sender’s email client to the recipient’s email server.

4.1 Key Characteristics of SMTP

4.2 How SMTP Works

SMTP operates through a client-server model. The process involves multiple steps to deliver an email successfully:

The process can be visualized as follows:


Client --> SMTP --> Sender's Mail Server --> SMTP --> Recipient's Mail Server --> Inbox

4.3 SMTP Commands

SMTP uses a set of standard commands to initiate and manage the email-sending process. Key commands include:


HELO example.com
MAIL FROM:<[email protected]>
RCPT TO:<[email protected]>
DATA
Subject: Test Email

This is a test email message.
.
QUIT

The "DATA" command is used to send the actual email content, and the email is terminated with a single period (".") on a line by itself.

4.4 SMTP Authentication and Security

To ensure that email transmission is secure, SMTP often employs authentication and encryption mechanisms. These include:


# Using SSL/TLS for secure email transmission
STARTTLS

4.5 Common SMTP Response Codes

When an SMTP command is issued, the server responds with a numeric status code to indicate the result. Common SMTP response codes include:


# Sample SMTP response codes during communication
220 smtp.example.com ESMTP Service ready
250 OK
354 Start mail input; end with <CRLF>.<CRLF>
550 Requested action not taken: Mailbox unavailable

4.6 Example of SMTP in Code

Here is an example of how to send an email using Python's smtplib library:


import smtplib
from email.mime.text import MIMEText

# Email details
sender = "[email protected]"
recipient = "[email protected]"
subject = "Test Email"
body = "This is a test email."

# Create the email message
msg = MIMEText(body)
msg["Subject"] = subject
msg["From"] = sender
msg["To"] = recipient

# SMTP server configuration
smtp_server = "smtp.example.com"
smtp_port = 587
smtp_user = "username"
smtp_password = "password"

# Establish a connection to the SMTP server
with smtplib.SMTP(smtp_server, smtp_port) as server:
    server.starttls()  # Secure the connection
    server.login(smtp_user, smtp_password)  # Log in to the SMTP server
    server.sendmail(sender, recipient, msg.as_string())  # Send the email
    print("Email sent successfully!")

In this example, we use the smtplib library to establish a connection with an SMTP server and send an email. The connection is secured using starttls(), and the server requires authentication before sending the email.

5. File Transfer Protocol (FTP)

File Transfer Protocol (FTP) is a standard network protocol used for transferring files between a client and a server over a TCP/IP network. FTP is designed to enable users to upload, download, and manage files on remote servers. It operates on a client-server model and can work in either active or passive mode depending on the configuration of the server and firewall settings.

5.1 Key Characteristics of FTP

5.2 FTP Commands

FTP uses a range of commands for file management and navigation on the server. Common FTP commands include:


USER username
PASS password
LIST
RETR example.txt
STOR upload.txt
QUIT

5.3 How FTP Works

FTP follows a straightforward process for file transfers between a client and a server:


# FTP Process Overview:
Client --> Control Channel (port 21) --> Server
Client --> Data Channel (port 20) --> Server (for file transfer)

5.4 Active vs. Passive FTP Modes

FTP can operate in two modes: active and passive. The difference lies in how the data connection is established:

5.4.1 Active Mode

In active mode, the client opens a random port and informs the server, which then initiates the data connection from its port 20 to the client’s specified port. This mode may face issues with firewalls since the server initiates the connection to the client.

5.4.2 Passive Mode

In passive mode, the server opens a random port and informs the client, which then initiates the data connection. This is more firewall-friendly because the client initiates both the control and data connections.


# Active Mode (client opens port, server connects back)
Client --> Control Channel --> Server (port 21)
Server --> Data Channel --> Client (random port)

# Passive Mode (client connects to server's random port)
Client --> Control Channel --> Server (port 21)
Client --> Data Channel --> Server (random port)

5.5 Security Concerns with FTP

Since FTP transmits data in plain text, including login credentials, it is susceptible to security risks such as eavesdropping, data tampering, and man-in-the-middle attacks. To address these issues, two secure alternatives to FTP are widely used:

5.6 Example of FTP in Code

Here is a basic example of using Python's ftplib to connect to an FTP server, list files, and download a file:


import ftplib

# FTP server details
ftp_server = "ftp.example.com"
ftp_user = "username"
ftp_password = "password"

# Establish connection to the FTP server
ftp = ftplib.FTP(ftp_server)
ftp.login(ftp_user, ftp_password)

# List files in the current directory
ftp.retrlines('LIST')

# Download a file from the server
with open('downloaded_file.txt', 'wb') as file:
    ftp.retrbinary('RETR example.txt', file.write)

# Close the connection
ftp.quit()

This Python script connects to an FTP server, lists the files in the directory, and downloads a file using the RETR command.