0% found this document useful (0 votes)
9 views33 pages

Programming and Networking Basics Guide

The document is a comprehensive study guide covering core programming principles and networking concepts. It includes sections on programming principles, control flow, functions, object-oriented programming, basic data structures, and networking fundamentals, specifically the OSI model. Each section provides definitions, examples, and quick reference summaries for key concepts.
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)
9 views33 pages

Programming and Networking Basics Guide

The document is a comprehensive study guide covering core programming principles and networking concepts. It includes sections on programming principles, control flow, functions, object-oriented programming, basic data structures, and networking fundamentals, specifically the OSI model. Each section provides definitions, examples, and quick reference summaries for key concepts.
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

Programming & Networking

Fundamentals: Mastery List


A comprehensive study and reference guide covering core programming principles and
networking concepts.

Section One: Programming Principles


Variables, Data Types, and Memory
What is a variable and how is it stored in memory?

A variable is a named container that stores a value in the computer's memory. Think of it
as a labeled box where you can keep data[1]. Each variable has three properties:
Name: The identifier used to reference the variable (e.g., age, temperature)
Value: The actual data stored (e.g., 25, 98.6)
Type: The kind of data it holds (determines memory allocation and operations
allowed)
The computer allocates a specific memory location and size based on the variable's data
type.

What are the main primitive data types, and what are their memory requirements?

Data Size
Range/Purpose Example
Type (Typical)
int 4 bytes -2,147,483,648 to 2,147,483,647 age = 25
Decimal numbers (6-7 significant price =
float 4 bytes
digits) 19.99
Double precision decimals (15-17 pi =
double 8 bytes
significant digits) 3.14159
grade =
char 1 byte Single character (ASCII)
'A'
isActive =
bool 1 byte True or False
true
name =
string Variable Sequence of characters
"Alice"
How does type casting work, and why is it important?
Type casting converts a variable from one data type to another. There are two types:

Implicit (Automatic) Casting: The compiler automatically converts compatible


types (e.g., int to float)
x = 5 # int
y = x + 2.5 # x is automatically converted to float, result is 7.5
Explicit (Manual) Casting: The programmer explicitly specifies the conversion
x=5
y = float(x) # Explicitly convert int to float: 5.0
z = int(9.8) # Explicitly convert float to int: 9 (truncates decimal)
Warning: Explicit casting can lead to data loss. Converting 9.8 to int loses the decimal
portion.

Quick Reference Summary


Variables are memory containers with name, value, and type
Primitive types determine memory size and valid operations
Type casting converts between compatible types (with potential data loss in explicit
conversions)

Control Flow: Conditionals and Loops


How do conditional statements work, and what are the main types?
Conditional statements execute different code blocks based on whether a condition is true
or false. They enable decision-making in programs.
Main Types:

Structur
Syntax Example Purpose
e
if (condition) { /*
if Execute block if condition is true
code */ }
if (condition) { } else {
if-else Two-way branching
}
if-else if-
Multiple conditions Multi-way branching
else
switch(variable) { Efficient multi-way branching for
switch
case value: } discrete values

Example: if-else-if structure


score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
else:
grade = 'F'
print(grade) # Output: B

What are loops, and what are the differences between loop types?
Loops repeat a block of code a specified number of times or until a condition is met.

Loop
Use Case Example
Type
Known number of for i in range(5): (iterate 5
for
iterations times)
Unknown iterations; while user_input != 'quit':
while
condition-based (repeat until user quits)
do- Execute at least once, Not common in Python; used in
while then check C/Java

Example: for loop

Print numbers 1 to 5
for i in range(1, 6):
print(i)

Output: 1 2 3 4 5
Example: while loop
count = 0
while count < 3:
print(f"Count: {count}")
count += 1
Output: Count: 0, Count: 1, Count: 2
What are loop control statements?

Loop control statements modify loop behavior:


break: Exit the loop immediately
continue: Skip the current iteration and continue to the next
pass: Do nothing (placeholder)
for i in range(10):
if i == 5:
break # Exit when i equals 5
print(i)

Output: 0 1 2 3 4
Quick Reference Summary
Conditionals (if-else, switch) make decisions based on conditions
Loops (for, while) repeat code blocks
Loop control (break, continue) alters loop execution

Functions, Scope, and Recursion


What is a function, and why are functions important?

A function is a reusable block of code that performs a specific task. Functions promote code
reusability, maintainability, and organization.
Basic Function Definition:
def greet(name):
"""Docstring: Function to greet a person"""
return f"Hello, {name}!"
result = greet("Alice")
print(result) # Output: Hello, Alice!

Function Components:
Parameters: Variables passed to the function
Return value: Data the function returns to the caller
Call: Executing the function with actual values (arguments)
What is scope, and what are the main types?

Scope determines where a variable can be accessed in a program.


Scope
Definition Lifetime Example
Type
From declaration
Variables declared x = 5 inside a
Local until function
inside a function function
ends
Globa Variables declared Entire program x = 5 at
l outside all functions execution module level
Variables in outer Functions
Enclo While outer
functions (nested inside
sing function executes
functions) functions
Built- Predefined len(), print(),
Entire program
in variables/functions True

Example:
x = 10 # Global scope
def my_function():
y = 5 # Local scope
print(x) # Can access global x
print(y) # Can access local y

my_function() # Output: 10, 5


print(x) # Output: 10
print(y) # Error: y is not defined outside function
What is recursion, and how does it work?
Recursion is when a function calls itself to solve a problem by breaking it into smaller
subproblems. Every recursive function must have a base case (stopping condition) to avoid
infinite loops.

Structure:
def recursive_function(problem):
if base_case_met:
return solution # Base case: stop recursion
else:
return recursive_function(smaller_problem) # Recursive case
Example: Factorial
def factorial(n):
# Base case
if n == 0 or n == 1:
return 1
# Recursive case
else:
return n * factorial(n - 1)
print(factorial(5)) # Output: 120 (5 * 4 * 3 * 2 * 1)
How does recursion trace execution?
factorial(5)
→ 5 * factorial(4)
→ 5 * 4 * factorial(3)
→ 5 * 4 * 3 * factorial(2)
→ 5 * 4 * 3 * 2 * factorial(1)
→ 5 * 4 * 3 * 2 * 1 (base case)

Recursion vs Iteration:
Recursion: Elegant for naturally recursive problems (trees, factorials), but slower
and uses more memory (call stack)
Iteration: Faster and uses less memory for most cases

Quick Reference Summary


Functions encapsulate reusable logic
Scope determines variable accessibility (local, global, enclosing, built-in)
Recursion solves problems by breaking them into smaller instances (requires base
case)

Object-Oriented Programming (OOP)


What is Object-Oriented Programming (OOP), and why is it useful?
OOP is a programming paradigm that models real-world concepts using objects (entities)
and classes (blueprints). It promotes code organization, reusability, and maintainability.
Core Benefits:

Modularity: Code organized into self-contained objects


Reusability: Classes can be reused across projects
Maintainability: Changes isolated to specific classes
Scalability: Easy to extend with new features
What is a class, and how do objects relate to classes?
A class is a blueprint that defines the structure and behavior of objects. An object is an
instance of a class.

Define a class (blueprint)


class Car:
def init(self, make, model):
[Link] = make
[Link] = model

def display_info(self):
return f"{[Link]} {[Link]}"

Create objects (instances)


car1 = Car("Toyota", "Camry")
car2 = Car("Honda", "Civic")
print(car1.display_info()) # Output: Toyota Camry
The Four Pillars of OOP:

Pillar Definition Example


Private variables
Encaps Bundling data and methods;
(self.__name), public
ulation hiding internal details
methods
Inherit Child classes inherit properties class SportsCar(Car):
ance from parent classes inherits from Car
Objects can take multiple forms;
Polymo Method overriding,
same interface, different
rphism method overloading
behavior
Abstrac Hiding complexity; showing only Abstract classes,
tion essential features interfaces

What is Encapsulation?
Encapsulation bundles data (attributes) and methods (functions) together, hiding internal
complexity from the outside.
class BankAccount:
def init(self, balance):
self.__balance = balance # Private attribute (hidden)

def deposit(self, amount):


if amount > 0:
self.__balance += amount
return f"Deposited ${amount}"

def get_balance(self): # Public method to access balance


return self.__balance
account = BankAccount(100)
[Link](50)
print(account.get_balance()) # Output: 150

account.__balance # Error: cannot access


private attribute directly
What is Inheritance?
Inheritance allows a child class to inherit attributes and methods from a parent class,
promoting code reuse.

Parent class
class Animal:
def init(self, name):
[Link] = name

def make_sound(self):
return "Generic sound"

Child class inherits from Animal


class Dog(Animal):
def make_sound(self):
return f"{[Link]} barks: Woof!"
dog = Dog("Buddy")
print(dog.make_sound()) # Output: Buddy barks: Woof!
What is Polymorphism?

Polymorphism allows objects of different classes to be treated through the same interface.
The same method name performs different actions based on the object type.
class Cat(Animal):
def make_sound(self):
return f"{[Link]} meows: Meow!"
Polymorphism: same method, different
behavior
animals = [Dog("Max"), Cat("Whiskers")]

for animal in animals:


print(animal.make_sound())

Output:
Max barks: Woof!
Whiskers meows: Meow!
What is Abstraction?
Abstraction hides complexity by showing only essential features and hiding
implementation details.

from abc import ABC, abstractmethod


class Vehicle(ABC):
@abstractmethod
def start_engine(self):
pass # Abstract method; must be implemented in child classes
class Motorcycle(Vehicle):
def start_engine(self):
return "Motorcycle engine started"

bike = Motorcycle()
print(bike.start_engine()) # Output: Motorcycle engine started

Quick Reference Summary


OOP models real-world concepts using objects (instances) and classes (blueprints)
Encapsulation: Bundle data and methods; hide internals
Inheritance: Child classes inherit from parent classes
Polymorphism: Same interface, different behaviors
Abstraction: Hide complexity; show essential features

Basic Data Structures: Arrays, Lists, and Dictionaries


What is an array, and how does it differ from a list?

An array is a fixed-size collection of elements of the same data type, stored in contiguous
memory locations.
A list is a dynamic collection that can grow or shrink and may contain mixed data types.
Feature Array List
Size Fixed Dynamic
Data Types Same type Mixed types allowed
Memory Contiguous Can be scattered
Access Time O(1) O(1)
Language C, Java (built-in) Python, JavaScript

Example: Array vs List

List (Python's alternative to arrays)


numbers_list = [1, 2, 3, 4, 5] # Dynamic
numbers_list.append(6) # Can grow
print(numbers_list) # Output: [1, 2, 3, 4, 5, 6]
mixed_list = [1, "hello", 3.14, True] # Mixed types
print(mixed_list) # Output: [1, 'hello', 3.14, True]
How do you access, insert, and delete elements in a list?

my_list = [10, 20, 30, 40, 50]

Access (indexing)
print(my_list[0]) # Output: 10 (first element)
print(my_list[-1]) # Output: 50 (last element)

Slicing
print(my_list[1:4]) # Output: [20, 30, 40]

Insert
my_list.insert(2, 25) # Insert 25 at index 2
print(my_list) # Output: [10, 20, 25, 30, 40, 50]
Delete
my_list.remove(25) # Remove by value
del my_list[0] # Delete by index
print(my_list) # Output: [20, 30, 40, 50]

Pop (remove and return last element)


last = my_list.pop()
print(last) # Output: 50
What is a dictionary, and what are its key features?

A dictionary is an unordered collection of key-value pairs. Each key must be unique and is
used to access its corresponding value. Dictionaries are efficient for lookups.
Characteristics:
Unordered (in older Python versions; ordered since Python 3.7)
Mutable (can be modified)
Keys must be unique and immutable (strings, numbers, tuples)
Values can be any data type

Example:
student = {
"name": "Alice",
"age": 20,
"gpa": 3.8,
"courses": ["Python", "Data Science", "Web Dev"]
}

Access value
print(student["name"]) # Output: Alice

Add new key-value pair


student["major"] = "CS"

Update value
student["age"] = 21
Delete key-value pair
del student["courses"]

Iterate through dictionary


for key, value in [Link]():
print(f"{key}: {value}")
Compare Arrays, Lists, and Dictionaries:

Operatio
Array List Dictionary
n
Create int arr[5] (C) my_list = [] my_dict = {}
arr[0] (by
Access list[0] dict["key"]
index)
append(), dict[key] =
Insert Fixed size
insert() value
Search O(n) O(n) O(1) average
Memory Fixed Dynamic Dynamic

Quick Reference Summary


Array: Fixed-size, same-type collection; fast access O(1)
List: Dynamic-size, mixed-type collection; flexible but slightly slower
Dictionary: Key-value pairs; O(1) average lookup; ideal for named access

Quick Reference: Programming Principles


Concept Definition Use Case
Named memory
Variables Store and manipulate data
containers
Data Classification of data (int, Determine memory size
Types float, string, etc.) and operations
Conditio Control execution based Make decisions (if-else,
nals on conditions switch)
Automate repetitive tasks
Loops Repeat code blocks
(for, while)
Function
Reusable code blocks Organize and reuse logic
s
Variable accessibility
Scope Prevent naming conflicts
region
Recursio Solve recursive problems
Function calling itself
n (trees, factorials)
Classes Blueprints for objects Structure complex data
Encapsul
Hide internal details Protect data integrity
ation
Inheritan
Child inherits from parent Promote code reuse
ce
Polymorp Multiple forms of same
Flexible, extensible code
hism interface
Abstracti
Hide complexity Show only essentials
on
Dynamic ordered
Lists Flexible data storage
collection
Dictionar
Key-value pairs Named access to data
ies
Section Two: Networking Fundamentals
The OSI Model (7 Layers)
What is the OSI Model?
The OSI (Open Systems Interconnection) Model is a standardized framework that
describes how communication systems transmit data over networks. It divides network
communication into 7 layers, each with specific functions. This layered approach allows
different technologies to work together seamlessly[2].

Figure 1: Figure 1: OSI Model - 7 Layers of Network Communication


What are the 7 layers of the OSI Model?
The OSI Model is divided into three categories:

Software Layers (Top 3):


Lay
Name Function Examples
er
Applica User interactions, HTTP, HTTPS, SMTP,
7
tion applications, services FTP, SSH, DNS
Present Data translation, SSL/TLS encryption,
6
ation encryption, compression JPEG compression
Establishes, maintains, Session tokens, login
5 Session
terminates connections sessions

Transport Layer (Middle):

Lay
Name Function Examples
er
Transp End-to-end communication, TCP (reliable), UDP
4
ort reliability (fast)

Hardware Layers (Bottom 3):

Lay
Name Function Examples
er
Netwo IP addresses,
3 Logical addressing, routing
rk routing protocols
Data Physical addressing, frame MAC addresses,
2
Link delivery Ethernet, Wi-Fi
Physic Transmission of raw bits Cables, fiber optics,
1
al over physical media radio waves

Layer 7 - Application Layer (User Interface)


This is where end users interact with the network. Applications and services operate here.
Key Protocols:

HTTP/HTTPS: Web browsing (HTTP is unencrypted; HTTPS is encrypted with


SSL/TLS)
SMTP : Email sending
POP3/IMAP : Email retrieval
FTP : File transfer
SSH: Secure command-line access
DNS: Domain name resolution (translates domain names to IP addresses)
Telnet: Remote login (unencrypted, use SSH instead)
Layer 6 - Presentation Layer (Translation & Formatting)

This layer ensures data is in a format that the application layer understands. It handles
translation, encryption, and compression.
Functions:
Encryption/Decryption: Convert plaintext to ciphertext and vice versa
Compression: Reduce file size (e.g., JPEG, PNG)
Translation: Convert between different character sets (ASCII, Unicode)

Example: When you download an image, the presentation layer decompresses it into a
viewable format.
Layer 5 - Session Layer (Connection Management)
This layer establishes, maintains, and terminates connections between devices. It manages
conversations between applications.

Functions:
Session Establishment: Create connection between applications
Session Maintenance: Keep connection alive, handle timeouts
Session Termination: Gracefully close connections
Example: When you log into a website, the session layer maintains your login state.

Layer 4 - Transport Layer (End-to-End Delivery)


This layer manages reliable or fast data transfer between applications on different hosts.
Protocols:

Proto Spee
Reliability Use Case
col d
Reliable (guarantees Slow Email, web browsing,
TCP
delivery, ordered) er file transfer
Unreliable (fast, no Faste Video streaming, online
UDP
guarantee) r gaming, VoIP

TCP Example:
Client → Server: "I want to send data" (connection established)
Data transfer with acknowledgments (guaranteed delivery)
Graceful close
UDP Example:
Client → Server: Send packet (fire and forget)
No acknowledgment; lost packets ignored
Layer 3 - Network Layer (Logical Addressing & Routing)
This layer handles logical addressing (IP addresses) and determines the best path for data
to travel across networks.

Key Functions:
IP Addressing: Assign unique addresses (IPv4, IPv6)
Routing: Forward packets to correct destination
Logical Segmentation: Divide networks using subnets
Key Protocols:

IP (Internet Protocol): Logical addressing


ICMP (Internet Control Message Protocol): Error reporting, ping utility
IGMP (Internet Group Management Protocol): Multicast group management
Layer 2 - Data Link Layer (Physical Addressing & Frame Delivery)
This layer uses MAC (Media Access Control) addresses to deliver frames to devices on the
same local network.

Functions:
MAC Addressing: Identify devices on local network (e.g., 00:1A:2B:3C:4D:5E)
Frame Assembly: Wrap data into frames
Switching: Forward frames between devices on same network
Key Technologies:

Ethernet: Wired LAN standard


Wi-Fi (802.11): Wireless LAN standard
Switches: Devices that forward frames based on MAC addresses
Layer 1 - Physical Layer (Transmission of Raw Bits)
This layer represents the actual physical medium through which data travels.

Physical Media:
Copper cables: Twisted pair (Cat5, Cat6), coaxial
Fiber optic cables: High-speed, long-distance
Wireless: Radio waves, infrared
Functions:

Convert bits to electrical/optical signals


Transmit over physical medium
Handle hardware specifications (voltage levels, cable standards)
How Data Flows Through OSI Layers:
Sending (Top to Bottom):
Application (Layer 7): User creates email
Presentation (Layer 6): Encrypt and compress
Session (Layer 5): Establish connection
Transport (Layer 4): Add TCP/UDP header
Network (Layer 3): Add IP header (source/destination IP)
Data Link (Layer 2): Add MAC header (source/destination MAC)
Physical (Layer 1): Convert to bits and transmit over cable/wireless
Receiving (Bottom to Top):
Physical (Layer 1): Receive bits from cable/wireless
Data Link (Layer 2): Remove MAC header, verify destination MAC
Network (Layer 3): Remove IP header, verify destination IP
Transport (Layer 4): Remove TCP/UDP header, ensure reliable delivery
Session (Layer 5): Verify session is active
Presentation (Layer 6): Decrypt and decompress
Application (Layer 7): Display email to user

Quick Reference Summary


OSI Model has 7 layers for standardized network communication
Software layers (5-7) handle applications and data formatting
Transport layer (4) bridges software and hardware
Hardware layers (1-3) handle physical transmission and routing

TCP/IP Suite and the Three-Way Handshake


What is the TCP/IP Suite?
The TCP/IP Suite is a hierarchical protocol suite used for modern internet communication.
It simplifies the OSI Model into 4 layers[3]:

TCP/IP
OSI Layers Purpose
Layer
5-7 (Session, Presentation, HTTP, FTP, DNS,
Application
Application) SMTP, SSH
Transport 4 (Transport) TCP, UDP
IP (IPv4, IPv6), ICMP,
Internet 3 (Network)
IGMP
Network
1-2 (Physical, Data Link) Ethernet, Wi-Fi, PPP
Access

What is TCP, and what makes it different from UDP?


TCP (Transmission Control Protocol):
Connection-oriented: Establishes connection before data transfer
Reliable: Guarantees all data arrives in correct order
Error checking: Detects and retransmits lost packets
Slower: Extra overhead for reliability
Use cases: Email, web browsing, file transfer, banking
UDP (User Datagram Protocol):

Connectionless: Sends data without establishing connection


Unreliable: No guarantee of delivery or order
Fast: Minimal overhead
Use cases: Video streaming, online gaming, DNS queries, VoIP
TCP vs UDP Comparison:

Feature TCP UDP


Connection Establishes connection No connection
Reliability Guaranteed delivery Best effort
Ordering Ordered delivery No ordering
Speed Slower (reliable) Faster (unreliable)
Error Checking Extensive Minimal
Header Size 20-60 bytes 8 bytes
Congestion Control Yes No
Example Protocol HTTP, SMTP, SSH DNS, DHCP, RTP

What is the TCP Three-Way Handshake?

The TCP Three-Way Handshake is a process that establishes a TCP connection between a
client and server. It synchronizes both parties and ensures reliable communication can
begin[4].
The Three Steps:
Step 1: SYN (Synchronize)

Client initiates: Sends a TCP packet with the SYN flag set
Includes: Client's Initial Sequence Number (ISN) - a random starting number
Purpose: "I want to start a connection, and here's my starting sequence number"
Step 2: SYN-ACK (Synchronize-Acknowledge)
Server responds: Sends a TCP packet with SYN and ACK flags set
Includes: Server's ISN and acknowledgment of client's ISN (Client ISN + 1)
Purpose: "I acknowledge your sequence number, and here's mine"

Step 3: ACK (Acknowledge)


Client confirms: Sends a TCP packet with ACK flag set
Includes: Acknowledgment of server's ISN (Server ISN + 1)
Purpose: "I acknowledge your sequence number; we're ready to communicate"
State after handshake: Both client and server are in the ESTABLISHED state, and data
transfer begins.

Visual Representation:
Client Server
||
|--- SYN (seq=100) ------------>|
| [SYN received]
|<-- SYN-ACK (seq=300, ack=101)-|
| [SYN-ACK received] |
|--- ACK (seq=101, ack=301) --->|
| [ESTABLISHED]
|========== Data Transfer ======|
| (both ESTABLISHED) |
Why is the Three-Way Handshake important?

1. Synchronization: Both sides agree on starting sequence numbers


2. Reliability: Confirms both ends are reachable and ready
3. Ordered Delivery: Sequence numbers ensure data arrives in order
4. Error Detection: Any lost packets are detected using sequence numbers
5. Flow Control: Prevents overwhelming the receiving end
Example Handshake in Real Scenario:
Client ([Link]) connecting to Web Server ([Link]):

Step 1: Client → Server


SYN flag set
Sequence number = 1000
Port = 50000 (client) → 80 (server)
Step 2: Server → Client

SYN and ACK flags set


Sequence number = 5000
Acknowledgment = 1001 (received 1000, expects 1001)
Port = 80 (server) → 50000 (client)
Step 3: Client → Server
ACK flag set
Sequence number = 1001
Acknowledgment = 5001 (received 5000, expects 5001)
Port = 50000 (client) → 80 (server)

Result: Connection established; both sides synchronized


TCP Connection Termination (Four-Way Handshake):
After data transfer, the connection closes:
Client Server
|--- FIN (seq=1100) ---------->|
| [FIN received]
|<---- ACK (ack=1101) ---------|
|<---- FIN (seq=5200) ---------|
| [FIN received]
|---- ACK (ack=5201) -------->|
| [Connection closed]

Quick Reference Summary


TCP/IP Suite simplifies OSI into 4 layers
TCP : Reliable, connection-oriented, slower (email, web, banking)
UDP : Fast, connectionless, unreliable (streaming, gaming, DNS)
Three-Way Handshake: SYN → SYN-ACK → ACK (establishes connection)
Sequence numbers ensure ordered, reliable delivery

IP Addressing: Public vs. Private and Subnetting


What is an IP Address, and what are IPv4 and IPv6?
An IP Address is a unique numerical identifier assigned to each device on a network. It
enables routing and delivery of data across networks.
IPv4 (Internet Protocol Version 4):

Format: 32-bit address; represented as 4 octets (0-255), e.g., [Link]


Total addresses: 2^32 = 4,294,967,296 addresses
Status: Widely deployed; running out of addresses
IPv6 (Internet Protocol Version 6):
Format: 128-bit address; represented in hexadecimal, e.g.,
2001:0db8:85a3::8a2e:0370:7334
Total addresses: 2^128 = 340 undecillion addresses
Status: Designed to replace IPv4; slow adoption

IPv4 vs IPv6 Comparison:


Feature IPv4 IPv6
Address Length 32 bits 128 bits
Format Decimal (0-255.0-255.0-255.0-255) Hexadecimal
Address Space 4.3 billion 340 undecillion
Example [Link] 2001:db8::1
Header Size 20 bytes 40 bytes
NAT Required Yes (addresses limited) No
Deployment Nearly universal Growing

What are public and private IP addresses?


Public IP Addresses:

Globally unique and routable on the internet


Assigned by IANA (Internet Assigned Numbers Authority)
Allow devices to communicate over the internet
Examples: Google DNS [Link], Cloudflare DNS [Link]
Private IP Addresses:
Not routed on the internet; reserved for internal networks
Reusable across different organizations (hidden behind NAT)
Used for local communication within organizations
Defined by RFC 1918

Private IP Address Ranges (IPv4):

Class Range Size Use Case


Class [Link] to 16.7
Large organizations
A [Link] million
Class [Link] to
1 million Medium organizations
B [Link]
Class [Link] to Small offices, home
65,536
C [Link] networks

Example: Your home router typically uses [Link]/24, assigning addresses like
[Link], [Link], etc.
How does NAT (Network Address Translation) work?
NAT allows private IP addresses to communicate with the public internet by translating
them to a public IP address.
Process:
Internal Device ([Link])

NAT Router translates to public IP (e.g., [Link])

Request sent to internet

Response returns to public IP

NAT Router translates back to private IP ([Link])

Device receives response

Benefit: Allows multiple private devices to share one public IP address, improving security
and conserving public IP addresses.
What is subnetting, and how does it work?
Subnetting divides a large network into smaller, manageable subnetworks (subnets). It
improves network efficiency, security, and organization.

Components:
Network Address: Identifies the subnet (all host bits = 0)
Subnet Mask: Determines which bits are network and which are host
Broadcast Address: Identifies all devices in subnet (all host bits = 1)
Usable Host Addresses: Range between network and broadcast
Subnet Mask Examples:

Notati
Mask Meaning
on
255.255.255. First 24 bits = network; last 8 bits = hosts
/24
0 (256 addresses)
255.255.255. First 25 bits = network; last 7 bits = hosts
/25
128 (128 addresses)
255.255.254. First 23 bits = network; last 9 bits = hosts
/23
0 (512 addresses)

Subnetting Example:
Network: [Link]/24
Breaking it into two /25 subnets:

Subnet 1:
Network: [Link]
Broadcast: [Link]
Usable hosts: [Link] to [Link] (126 addresses)
Subnet 2:

Network: [Link]
Broadcast: [Link]
Usable hosts: [Link] to [Link] (126 addresses)
Advantages of Subnetting:
Network Organization: Separate departments or functions
Improved Security: Isolate sensitive networks
Reduced Broadcast Traffic: Broadcasts limited to subnet
Better Performance: Smaller collision domains
IP Address Conservation: Efficient use of address space

Quick Reference Summary


IPv4: 32-bit addresses; 4.3 billion total
IPv6: 128-bit addresses; designed for future internet
Public IPs: Globally routable; unique
Private IPs: Internal only; reusable (10.x.x.x, 172.16-31.x.x, 192.168.x.x)
NAT: Translates private to public IPs
Subnetting: Divides networks into manageable subnetworks

Core Network Protocols


What is DNS (Domain Name System), and how does it work?
DNS translates human-readable domain names into IP addresses, enabling users to access
websites by name instead of IP address.

Process:
User types: [Link] in browser

DNS Resolver (usually ISP) queries root nameserver

Root nameserver responds with TLD (Top-Level Domain) server address

TLD server responds with authoritative nameserver address

Authoritative nameserver responds with IP address (e.g., [Link])

Browser connects to IP address; website loads
DNS Record Types:
Type Purpose Example
Maps domain to IPv4
A [Link] → [Link]
address
AAA Maps domain to IPv6 [Link] →
A address 2606:2800:220:1:248:1893:25c8:1946
CNA Alias (canonical
[Link] → [Link]
ME name)
Mail exchange
MX Points to mail server
(email server)
NS Nameserver Points to authoritative nameserver
TXT Text records Verification, SPF, DKIM

What is DHCP (Dynamic Host Configuration Protocol)?


DHCP automatically assigns IP addresses and other network configurations to devices,
eliminating manual configuration.

Process:
1. DISCOVER: Client broadcasts "I need an IP address"
2. OFFER: DHCP server responds with available IP
3. REQUEST: Client requests the offered IP
4. ACK: Server confirms the assignment
Result: Device receives IP, gateway, DNS servers, and lease time

Benefits:
Simplifies network management
Prevents duplicate IP assignments
Automatic configuration of DNS servers and gateways
IP addresses recycled when devices leave network
Lease Time: IP is temporarily assigned (e.g., 24 hours). Device must renew before
expiration.

What are HTTP and HTTPS?


HTTP (HyperText Transfer Protocol):
Unencrypted web communication protocol
Runs on port 80
Vulnerable to eavesdropping (plain text visible)
Status: Deprecated for sensitive data

HTTPS (HTTP Secure):


Encrypted web communication using SSL/TLS
Runs on port 443
All data encrypted; secure against eavesdropping
Uses SSL/TLS certificates for authentication
Status: Industry standard; required for sensitive sites
HTTP Request Example:

GET /[Link] HTTP/1.1


Host: [Link]
User-Agent: Mozilla/5.0
Accept: text/html
[Server responds with status and content]
HTTPS Encryption Process:

Browser → Server: "I want secure communication"


Server → Browser: SSL certificate (public key)
Browser generates symmetric key, encrypts with server's public key
Exchange of encrypted symmetric key
Encrypted communication using symmetric key
What is FTP (File Transfer Protocol)?
FTP transfers files between computers over a network.

Characteristics:
Unencrypted (credentials visible)
Uses two connections: Control (port 21) and Data (port 20)
Authentication required (username/password)
Status: Legacy; replaced by SFTP for security
Example FTP Session:

1. Connect to FTP server (port 21)


2. Send username and password
3. Navigate directories
4. Upload/download files (port 20)
5. Close connection
What is SSH (Secure Shell)?
SSH provides secure remote command-line access and file transfer.

Characteristics:
Encrypted communication (secure alternative to Telnet)
Uses public-key cryptography for authentication
Runs on port 22
Supports SFTP (Secure FTP) for encrypted file transfer
SSH Example:
ssh user@[Link]

Prompts for password or uses SSH key


Secure command-line access to remote
server
Benefits:
Encrypted credentials
Remote administration
Port forwarding capabilities
Secure file transfer (SFTP, SCP)

Comparison of Core Protocols:

Proto Encrypti
Port Use Case Status
col on
Domain name
DNS 53 No Active
resolution
67/6 IP address
DHCP No Active
8 assignment
Deprecated (use
HTTP 80 No Web browsing
HTTPS)
HTTP Yes Secure web
443 Standard
S (SSL/TLS) browsing
20/2 Legacy (use
FTP No File transfer
1 SFTP)
Secure remote
SSH 22 Yes Standard
access
25/5
SMTP Optional Email sending Active
87
POP3 110 Optional Email retrieval Active
Email retrieval
IMAP 143 Optional Active
(advanced)
Quick Reference Summary
DNS: Translates domain names to IP addresses
DHCP : Automatically assigns IP addresses and network configuration
HTTP/HTTPS: Web protocols; HTTPS is encrypted and secure
FTP : File transfer (legacy; use SFTP)
SSH: Secure remote access and encrypted file transfer

Network Hardware: Routers, Switches, and Firewalls


What is a Router, and what does it do?

A Router connects multiple networks and forwards data packets between them using IP
addresses (Layer 3).
Functions:
Forwarding: Routes packets to correct destination network
IP Routing: Uses routing tables to determine best path
NAT: Translates private IPs to public IPs
DHCP Server: Assigns IP addresses to local devices
Firewall: Basic packet filtering (many routers include this)

Router Types:

Type Use Case Example


Residential Router Home/small office WiFi router from ISP
Enterprise Router Large networks Cisco ASR, Juniper MX
Edge Router Network boundary Connects to ISP
Core Router Internet backbone Handles massive traffic

Example Router Function:


Packet from [Link] destined for [Link]

Router receives packet

Routing table: [Link]/24 is reachable via port 2

Router forwards packet out port 2

Packet reaches destination network

What is a Switch, and how does it differ from a Router?


A Switch connects devices within the same network and forwards data using MAC
addresses (Layer 2).
Key Differences:

Feature Router Switch


Layer Layer 3 (Network) Layer 2 (Data Link)
Addressing IP addresses MAC addresses
Connections Different networks Same network
Traffic Between networks Within network
Broadcast Stops broadcasts Forwards broadcasts
Ports Few (2-4 typically) Many (24-48+)
Cost Higher Lower

Switch Functions:

Learning: Builds MAC address table (learns which MAC on which port)
Forwarding: Sends frames to correct port based on destination MAC
Flooding: Sends broadcast/unknown frames to all ports except incoming
Example Switch Operation:
Device A (MAC: AA:AA:AA:AA:AA:AA) on port 1

Device A sends frame to Device B (MAC: BB:BB:BB:BB:BB:BB)

Switch checks MAC table: BB:BB:BB:BB:BB:BB is on port 3

Switch forwards frame only to port 3

Device B receives frame; other devices don't see it (improves efficiency)

What is a Firewall, and how does it protect networks?


A Firewall is a security device that monitors and controls incoming and outgoing network
traffic based on rules.
Types of Firewalls:
Lay
Type Function Example
er
Stateless Examines each packet Hardware
3-4
Firewall individually firewall
Stateful Tracks connection state; Most modern
3-4
Firewall remembers past packets firewalls
Web
Application Inspects application-level
7 application
Firewall (WAF) data
firewall
Inspects content before
Proxy Firewall 7 Content filter
forwarding

Firewall Rules Example:


Rule 1: ALLOW all outgoing traffic (trusted)
Rule 2: ALLOW incoming traffic on port 443 (HTTPS)
Rule 3: ALLOW incoming traffic on port 22 from admin subnet only (SSH)
Rule 4: DENY all other incoming traffic (default deny)

Key Security Features:


Packet Filtering: Allow/block based on IP, port, protocol
Stateful Inspection: Track connection state
Application Inspection: Deep packet inspection
VPN Support: Secure remote access
Intrusion Detection: Detect malicious patterns
Firewall Placement:

Internet

[FIREWALL] ← Perimeter defense

Router

Internal Network
Hardware vs Software Firewall:
Aspect Hardware Software
Location Network perimeter Individual device
Protection Entire network Single device
Performance Impact Minimal May slow device
Management Centralized Per-device
Cost Higher Usually free
Use Case Enterprise Personal computers

Quick Reference Summary


Router: Connects networks; uses IP addresses (Layer 3)
Switch: Connects devices on same network; uses MAC addresses (Layer 2)
Firewall: Monitors and controls traffic; enforces security rules
Placement: Router at network boundary; switches inside network; firewall at
perimeter

Quick Reference: Networking Fundamentals


Compo Lay
Function Example
nent er
OSI Standardizes network
1-7 Physical → Application
Model communication
Reliable, ordered
TCP 4 Email, web browsing
delivery
Fast, unreliable Video streaming,
UDP 4
delivery gaming
Logical addressing and
IP 3 [Link], [Link]/8
routing
Physical addressing
MAC 2 00:1A:2B:3C:4D:5E
(local network)
Domain name [Link] →
DNS 7
resolution [Link]
Automatic IP
DHCP 7 ISP assigns [Link]
assignment
HTTP/H
7 Web communication Port 80/443
TTPS
SSH 7 Secure remote access Port 22, encrypted
Network Connects [Link]/24
Router 3
interconnection to [Link]/24
Connects computers on
Switch 2 Device interconnection
same network
Firewal Traffic control & Block/allow packets
3-7
l security based on rules

References
[1] Duke University. (2025). Data: Types, Values, Variables, and Names. Retrieved from http
s://[Link]/jupyternotebooks/
[2] Corero. (2025). What is the OSI Model? The 7 Layers Explained. Retrieved from [Link]
[Link]/what-is-the-osi-model/
[3] Codecademy. (2025). TCP 3-Way Handshake: How Does it Work? Retrieved from [Link]
[Link]/resources/blog/what-is-tcp
[4] CloudMyLab. (2025). Understanding the TCP/IP 3-Way Handshake. Retrieved from http
s://[Link]/tcp-ip-3-way-handshake

Document Version: 1.0


Last Updated: December 19, 2025
For Educational Purposes: This guide is designed for beginners and intermediate learners
studying computer science fundamentals.

You might also like