Computer Networks

Syllabus UNIT I: Introduction
Types of Computer Networks, Reference Models- The OSI Reference Model, The TCP/IP Reference Model, A Critique of the OSI Model and Protocols, A Critique of the TCP/IP Reference Model. Network Devices.
UNIT II: The Data Link Layer
Transmission Media- Guided and Un-guided media, Data Link Layer Design Issues, Services Provided to the Network Layer, Error detecting and Error Correcting codes, Elementary Data Link Protocols, Sliding Window Protocols, HDLC, PPP. Multiple Access Protocols: Wired LAN – Ethernet, Fast Ethernet, Gigabit Ethernet.
UNIT III: The Network Layer
Network Layer Design Issues, Routing Algorithms, Congestion, Congestion control algorithms. The Network Layer in the Internet, IPv6, The IPv4 Protocol, IP Addresses- Classful, CIDR, NAT, IP Version 6 Protocol, Transition from IPV4 to IPV6.
UNIT IV: The Transport Layer
The Transport Layer Services, Transport Layer Protocols: UDP, TCP and SCTP
UNIT V: The Application Layer
The World Wide Web, HTTP, Domain Name Space, Remote Login, Electronic Mail and File Transfer


LAB Syllabus: 

1. Study of Network devices in detail and connect the computers in Local Area Network.
2. Write a Program to implement the data link layer framing methods such as
   i) Character stuffing  ii) Bit stuffing.
3. Write a Program to implement data link layer framing method checksum.
4. Write a program for Hamming Code generation for error detection and correction.
5. Write a Program to implement on a data set of characters the three CRC polynomials – CRC 12, CRC 16 and CRC CCIP.
6. Write a Program to implement Sliding window protocol for Goback N.
7. Write a Program to implement Sliding window protocol for Selective repeat.
8. Write a Program to implement Stop and Wait Protocol.
9. Write a program for congestion control using leaky bucket algorithm
10. Write a Program to implement Dijkstra‘s algorithm to compute the Shortest path through a graph.
11. Write a Program to implement Distance vector routing algorithm by obtaining routing table at each node (Take an example subnet graph with weights indicating delay between nodes).
12. Write a Program to implement Broadcast tree by taking subnet of hosts.
13. Wireshark
  i. Packet Capture Using Wireshark
  ii. Starting Wireshark
  iii. Viewing Captured Traffic
  iv. Analysis and Statistics & Filters.
14. How to run Nmap scan
15. Operating System Detection using Nmap
16. Do the following using NS2 Simulator
  i. NS2 Simulator – Introduction
  ii. Simulate to Find the Number of Packets Dropped
  iii. Simulate to Find the Number of Packets Dropped by TCP/UDP
  iv. Simulate to Find the Number of Packets Dropped due to Congestion
  v. Simulate to Compare Data Rate & Throughput.

TextBooks TexBook1:Andrew S. Tanenbaum - Computer Networks-PDF Link
TextBook2:Data-Communications-and-Network-5e- Behrouz-A.Forouzan- PDF Link
Weblinks Swayam Course Enroll/Register:Link
NPTEL Archive:Link
GATE exam info GATE Exam Paper: Link
GATE Syllabus (Page 67 for CSE): Link
Previous Papers R20 Syllabus and Question Papers: Link
Materials from other Colleges (You must read according to our syllabus)
Folder of Materials: Link
DCN Material: Link
Syllabus: Overview
UNIT I: Introduction
# Discusses types of computer networks and the structure of OSI and TCP/IP reference models.
# Covers critique of both models and introduces basic network devices like routers, switches, etc.
UNIT II: The Data Link Layer
# Explores guided/unguided transmission media and error control methods like CRC and Hamming code.
# Describes data link protocols (HDLC, PPP) and multiple access techniques including Ethernet standards.
UNIT III: The Network Layer
# Focuses on routing algorithms, congestion control, and IP addressing schemes (IPv4, IPv6).
# Explains design issues in network layer protocols and IPv4 to IPv6 transition mechanisms.
UNIT IV: The Transport Layer
# Explains services provided by the transport layer and connection management.
# Details protocols such as UDP, TCP, and SCTP with their features and differences.
UNIT V: The Application Layer
# Covers core internet services like HTTP, DNS, FTP, Telnet, and email protocols.
# Highlights the functionality and structure of the World Wide Web and domain name space.

Experiments mapping to Syllabus: 
Unit-I: Exp1
Unit-II: Exp 2 to 8
Unit-III: Exp 9 to 12
Exp 13: Units 2,3,4
Exp14,15: Units 3,4,5
Exp16: Unit3,4


Unit-I Material:
I. Types of Computer Networks
II. Reference Models- The OSI Reference Model, The TCP/IP Reference Model
III. A Critique of the OSI Model and Protocols
IV. A Critique of the TCP/IP Reference Model
V. Internet History


I. Types of Computer Networks:
Classified by size, geographical coverage, and ownership:
Local Area Network (LAN): Privately owned, single office/building/campus
LANs range from simple (two PCs, printer) to complex (audio/video devices)
Each LAN host has a unique address for packet communication
Wide Area Network (WAN): Spans towns, states, countries, or globally
WANs connect devices like switches, routers, modems; often leased
Point-to-Point WAN: Connects two devices via cable or air
Switched WAN: Multiple point-to-point WANs linked by switches
Internetwork: Connects LANs and WANs to form a private internet {Switching: Circuit-switched (dedicated) or packet-switched (store-and-forward

                     PAN                       LAN and WLAN                                        MAN


 
               WAN                               peer-to-peer                                        Internetwork




II. Reference Models

(a) The OSI Reference Model:
  • Developed by ISO for standardizing protocols (Open Systems Interconnection)
  • Seven layers, each with a specific function
  • Physical Layer: Transmits raw bits, handles signals, timing, connectors
  • Data Link Layer: Ensures error-free transmission via frames, acknowledgments
  • Data Link includes Medium Access Control (MAC) for shared channels
  • Network Layer: Manages packet routing, congestion, heterogeneous network interconnects
  • Transport Layer: End-to-end delivery, splits data, ensures correct arrival
  • Session Layer: Manages sessions, dialog control, token management, synchronization
  • Presentation Layer: Handles data syntax/semantics, standard encoding
  • Application Layer: Supports user applications (e.g., HTTP, FTP, SMTP)


GMAIL Example of OSI reference model:
OSI Layer 7 – Application Layer: i/f b/w s/w and n/w; Login/Logout/ HTTP/HTTPs connection; Compose; Send; 
OSI Layer 6 – Presentation Layer: encrypt contents (PDF/Word/ Images);
OSI Layer 5 – Session Layer: Active / Inactive sessions; 
OSI Layer 4 – Transport Layer: Packet lost is retransmitted using TCP
OSI Layer 3 – Network Layer: Packets sent; routing b/w sc and dt IP addresses
OSI Layer 2 – Data Link Layer: device communication to routers, using MAC address; error detection and correction;
OSI Layer 1 – Physical Layer: Binary data transmitted as either electrical signals (using Ethernet) or  as light (Optical Fiber)  or RadioWaves (Wi-Fi)

(b)The TCP/IP Reference Model:
  • Developed for ARPANET, focuses on robust internetworking
  • Four layers: Link, Internet, Transport, Application
  • Link Layer: Interfaces hosts with transmission links (e.g., Ethernet)
  • Internet Layer: Uses IP protocol for packet delivery across networks
  • Internet Layer supports connectionless communication, routing, congestion
  • Transport Layer: TCP (reliable, connection-oriented), UDP (unreliable, fast)
  • TCP ensures error-free delivery; UDP prioritizes speed (e.g., video streaming)
  • Application Layer: Includes protocols like HTTP, FTP, SMTP, DNS, RTP
  • Designed to survive hardware failures for continuous communication
  • No session or presentation layers, unlike OSI

GMAIL Example:
Application Layer: runs over HTTPS R/W/send emails via a browser or app.
Transport Layer: TCP to ensure emails and attachments are delivered reliably and in order.
Internet Layer: IP assigns addresses to route Gmail data packets across the internet from sender GSRV (Google Servers)
Link Layer: The data travels physically via Wi-Fi, Ethernet, or mobile networks to reach GSRV





III. Critique of the OSI Model and Protocols
  • The OSI model appeared after the TCP/IP protocol suite. 
  • Most experts were at first excited and thought that the TCP/IP protocol would be fully replaced by the OSI
  •  model. 
  • (a) OSI was completed when TCP/IP was fully in place and a lot of time and money had been spent on the suite; changing it
  •  would cost a lot.
  • (b) some layers in the OSI model were never fully defined. For example, although the services provided by the presentation and the session layers were listed in the document, actual protocols for these two layers were not fully defined, nor were they fully described, and the corresponding software was not fully developed. 
  • (c) OSI was implemented by an organization in a different application --> did not show high performance --> they switched back to TCP/IP

  • Bad Timing: Standardized too late, after TCP/IP adoption in academia
  • Bad Technology: Complex model/protocols, seven layers (some underutilized)
  • Session and presentation layers have minimal functionality
  • Data Link and Network layers overloaded with addressing, error control
  • Bad Implementations: Initial OSI systems were slow, unwieldy
  • Complexity caused poor performance, harming OSI’s reputation
  • Bad Politics: Seen as government-driven, not researcher-friendly
  • OSI protocols not widely adopted, though model remains useful
  • Convergence sublayers added to fix mismatches with real networks
  • Limited focus on internetworking, assumed single national networks


IV. Critique of the TCP/IP Reference Model
  • Does not distinguish services, interfaces, and protocols clearly
  • Model is TCP/IP-specific, not generalizable (e.g., unsuitable for Bluetooth)
  • Link Layer: More an interface than a true layer, lacks detail
  • Internet Layer: Effective for IP delivery, weak in congestion control
  • Transport Layer: Offers TCP (reliable) or UDP (fast), unlike OSI’s single mode
  • Model built after protocols, ensuring fit but limiting flexibility
  • Lacks session/presentation layers, leaving functions to applications
  • Strong in practice due to robust protocols (e.g., TCP, IP, HTTP)
  • Benefited from high-quality Berkeley UNIX implementation
  • Large user community drove improvements and adoption


V. Internet History
Early History:
* 1950s to 1960s --> Telephone and Telegraphs --> Circuit Switched
* Mid 1906s --> ARPANET (Advanced Research Projects Agency Network ) by US DoD (Department of Defense)  developed specialized computer called IMP (interface message processor (IMP);  Each IMP had to be able to communicate with other IMPs; Software called the Network Control Protocol (NCP) provided com
munication between the hosts;

Birth of Internet:
* a new version of NCP -->  transmission control protocol (TCP)
* TCP into two protocols: Transmission Control Protocol (TCP) and Internet Protocol (IP).
* IP would handle datagram routing
* TCP would be responsible for higher level functions such as segmentation, reassembly, and error.
* ARPANET = ARPANET (non-military) + MILNET (Military Network)
* CSNET (Computer Science Network) by NSF (National Science Foundation); No Redundancy; Slower transmission rate;
* NSFNET(National Science Foundation Network)connected five supercomputer centers; ARPANET was replaced by NSFNET;
* ANSNET(Advanced Network Services Network) replaced the NSFNET (unable to handle high traffic); Three companies (IBM, Merit, and Verizon) = formed the non-profit organization called the ANSNET.

Internet Today:
World Wide Web (WWW) this added commercial applications, Multimedia, Peer-to-Peer applications

Unit-1 Imp Questions/ ClassTest-Q/ Model Quiz

Q1. Explain about the importance of Internet and its history.
Q2. Critique the OSI reference model
Q3. Compare the OSI and TCP/IP reference models
Q4. Critique the TCP/IP reference model
Q5. What is computer network? Explain about LAN, WAN, MAN and Internetwork.


Model Quiz Questions
Q1. Mention any three types of computer networks.
Q2. List out any two phylosophical points for each model. (TCP/IP reference model and OSI reference model)
Q3. Full form of TCP/IP
Q4. Full form of OSI in OSI reference model and its significance.
Q5. Full form of ARPANET and its significance.
Q6. What is peer-to-peer communication.

Unit-2 Imp Questions/ ClassTest-Q/ Model Quiz

Q1. Explain about Coaxial pair cable, Twisted pair cable and fiber optic cable and unguided media. Analyze the advantages ofone overthe other.
Q2. Describe the services provided by Data Link Layer.
Q3. Define PPP. Describe in detail with a neat diagram.
Q4. Explain the purpose of cladding in optical fiber. Q5. What is the need for -error detection? Explain the methods used for error detection and error correction with typical examples.
Q6. Compare any three Multiple Access protocols
Q7.

CN Lab Programs
Bit Stuffing

#Experiment2b BitStuffing
# Experiment2b BitStuffing with user input and full-frame stuffing

def bit_stuffing(data):
    stuffed = '01111110'
    count = 0
    for bit in data:
        stuffed += bit
        if bit == '1':
            count += 1
            if count == 5:
                stuffed += '0'  # Stuff a 0 after five 1s
                count = 0
        else:
            count = 0
    return stuffed+'01111110'

def bit_unstuffing(stuffed):
    unstuffed = ''
    count = 0
    i = 8
    while i < len(stuffed)-8:
        bit = stuffed[i]
        unstuffed += bit
        if bit == '1':
            count += 1
            if count == 5:
                i += 1  # Skip stuffed 0
                count = 0
        else:
            count = 0
        i += 1
    return unstuffed

# --- Runtime input ---
data = input("Enter the binary data to be stuffed (including delimiters if any): ")

stuffed_bits = bit_stuffing(data)
unstuffed_bits = bit_unstuffing(stuffed_bits)

print("\nOriginal Bits:   ", data)
print("Stuffed Bits:    ", stuffed_bits)
print("Unstuffed Bits:  ", unstuffed_bits)
Character Stuffing

# Experiment2a Character Stuffing with correct escape logic (esc after flag/esc)
def character_stuffing(data, flag='F', esc='E'):
    stuffed_data = flag  # Start with the flag
    for char in data:
        if char == flag or char == esc:
            stuffed_data += esc  # Insert escape BEFORE special char
        stuffed_data += char
    stuffed_data += flag  # End with the flag
    return stuffed_data

def character_unstuffing(stuffed_data, flag='F', esc='E'):
    unstuffed_data = ''
    i = 1  # Skip starting flag
    while i < len(stuffed_data) - 1:
        if stuffed_data[i] == esc:
            i += 1  # Skip the escape character
        unstuffed_data += stuffed_data[i]
        i += 1
    return unstuffed_data

# --- Runtime input ---
data = input("Enter the data to be stuffed: ")
flag = input("Enter the flag character (delimiter): ")
esc = input("Enter the escape character: ")

stuffed = character_stuffing(data, flag, esc)
unstuffed = character_unstuffing(stuffed, flag, esc)

print("\nOriginal Data:   ", data)
print("Stuffed Data:    ", stuffed)
print("Unstuffed Data:  ", unstuffed)
Checksum

# Input two binary numbers as strings of equal length
n = int(input("Enter number of bits: "))   # length of binary numbers
a = input("Enter binary1: ")
b = input("Enter binary2: ")

# Convert to integer
a_int = int(a, 2)
b_int = int(b, 2)

# Sum
c = a_int + b_int
print('-------------------------')
print('sum=         ',(bin(c)[2:])) #9 spaces after =

# If sum exceeds n bits, add carry
max_val = 2 ** n
if c >= max_val:
    c = (c % max_val) + 1  # add carry

# Get n-bit binary sum
sum_bin = bin(c)[2:]

# Calculate checksum (1's complement)
checksum = ''.join('1' if x == '0' else '0' for x in sum_bin)

print("Sum      :", sum_bin)
print("Checksum :", checksum)

Hamming Code

#--------------------Transmitter Side
a=input('Enter a 4-bit binary data: ')
# print('\n as the input has 4-bits i.e., m=4, no of parity bits=3')
# print('2^p >= m+p+1')
# print('parity_bit locations are P1 =2^0 , P2 = 2^1, P4=  2^2, P8 = 2³.....')
# print('parity followed here is EVEN PARITY')
# print('P4= 5 xor 6 xor 7, P2 =3 xor 6 xor 7, P1 = 3 xor 5 xor 7 ')
# print('\nD7   D6  D5  P4  D3  P2  P1')
# print(a[0],'  ',a[1],' ',a[2],' ','P4',' ',a[3],'','P2','','P1')
#P4 = 0 if (int(a[0]) + int(a[1]) + int(a[2])) % 2 == 0 else 1
P4 = int(a[0]) ^ int(a[1]) ^ int(a[2])
P2 =0 if(int(a[3])+int(a[1])+int(a[0])) %2==0 else 1
P1 =0 if(int(a[3])+int(a[2])+int(a[0]))%2==0 else 1
print('\n the hamming code is as below:')
print('D7   D6  D5  P4  D3  P2  P1')
print(a[0],'  ',a[1],' ',a[2],' ',P4,' ',a[3],' ',P2,' ',P1)
txham=a[0]+a[1]+a[2]+str(P4)+a[3]+str(P2)+str(P1)
print('the 7-bit transmitted hamming code is: ',txham)
print('\n')

#------------------Receiver Side
r=input('enter the received 7-bit hamming code: ')
#r=received hamming code
P4C = int(r[0]) ^ int(r[1]) ^ int(r[2]) ^ int(r[3])
P2C = int(r[5]) ^ int(r[4]) ^ int(r[1]) ^ int(r[0])
P1C = int(r[6]) ^ int(r[4]) ^ int(r[2]) ^ int(r[0])
perr = f"{P4C}{P2C}{P1C}"
print('the error location in binary is: ', perr, 'while integer position is: ',int(perr,2))
print('Data is received without errors') if perr=="000" else print('*Retransmit the data*')

CRC

CRC-12 0x80F 12 0x000 Telecom, legacy protocols
CRC-16-IBM 0x8005 16 0x0000 USB, Modbus, IBM SDLC
CRC-CCITT 0x1021 16 0xFFFF X.25, Bluetooth, GSM, PPP
--------------------------------------
Theory: CRC12
Polynomial: x^12 + x^11 + x^3 + x^2 + x + 1
(Hex: 0x180F or 0x80F, sometimes also shown as 0xF13)
Length: 12 bits
Typical Usage: Telecom systems, CDMA, and some legacy communication protocols.
Properties: Detects all single-bit and double-bit errors.Good for short message frames due to limited length.
----
#python code
def crc12(data):
    poly = 0x80F
    crc = 0
    for byte in data:
        crc ^= (byte << 4)
        for _ in range(8):
            if (crc & 0x800):
                crc = ((crc << 1) ^ poly) & 0xFFF
            else:
                crc = (crc << 1) & 0xFFF
    return crc
----------------------------------------
Theory: CRC 16
Polynomial: x^16 + x^15 + x^2 + 1
(Hex: 0x8005 or 0x1021 for CCITT variant)
Length: 16 bits
Initial Value: Usually 0x0000 or 0xFFFF depending on standard.
Typical Usage: USB, Modbus, IBM SDLC, XMODEM.
Properties:    Widely used due to strong error-detection for up to 4K bits.Flexible with initial/final XOR and reflection options.
----------
#python code
def crc16(data):
    poly = 0x8005
    crc = 0x0000
    for byte in data:
        crc ^= (byte << 8)
        for _ in range(8):
            if (crc & 0x8000):
                crc = (crc << 1) ^ poly
            else:
                crc <<= 1
            crc &= 0xFFFF
    return crc
--------------------------------------------
Theory: CRC CCITT
CCITT stands for Comité Consultatif International Téléphonique et Télégraphique (French), which translates to International Telegraph and Telephone Consultative Committee in English.
CCITT was a standards body that developed and published recommendations for telecommunications, including protocols and error-checking codes.
It was a specialized agency under the International Telecommunication Union (ITU), a United Nations agency for information and communication technologies.The CCITT created standards for everything from telephone signaling to fax machines, modems, and data communication protocols.
----------
#python code
def crc_ccitt(data):
    poly = 0x1021
    crc = 0xFFFF
    for byte in data:
        crc ^= (byte << 8)
        for _ in range(8):
            if (crc & 0x8000):
                crc = (crc << 1) ^ poly
            else:
                crc <<= 1
            crc &= 0xFFFF
    return crc
--------------------------------------------------
Sliding Window Protocol for GO Back N
Working: 
Sender transmits frames 1, 2, 3, 4.
Receiver gets 1, 3, 4:
    ACKs 1, 3, 4
    Buffers 3, 4 since 2 is missing.
Sender times out for 2:
    Retransmits 2.
Receiver gets 2:
    Delivers 1, 2, 3, 4 in order to upper layer
-------------------------------------------
Algorithm:
TX:
for each frame in window:
    send(frame)
    start_timer(frame)
while ACK not received for frame:
    if timer expired:
        retransmit(frame)
    else:
        move window forward on receiving ACK
RX:
if frame within window and not already received:
    buffer(frame)
    send_ack(frame)
    if all previous frames received:
        deliver_in_order()
else:
    discard(frame)
-----------------------------
# python code
import random
import time

class Frame:
    def __init__(self, seq_num, data):
        self.seq_num = seq_num
        self.data = data
        self.acknowledged = False

class Sender:
    def __init__(self, window_size, seq_range):
        self.window_size = window_size
        self.seq_range = seq_range
        self.base = 0
        self.next_seq = 0
        self.window = []

    def send_frames(self, data_list):
        # Fill window initially
        for data in data_list:
            if len(self.window) < self.window_size:
                self.window.append(Frame(self.next_seq, data))
                print(f"Sender: Sending Frame {self.next_seq} with data: {data}")
                self.next_seq = (self.next_seq + 1) % self.seq_range

    def receive_ack(self, ack_seq):
        print(f"Sender: Received ACK for Frame {ack_seq}")
        for frame in self.window:
            if frame.seq_num == ack_seq:
                frame.acknowledged = True
        # Slide window
        while self.window and self.window[0].acknowledged:
            self.window.pop(0)

    def resend_lost_frames(self):
        for frame in self.window:
            if not frame.acknowledged:
                print(f"Sender: Resending Frame {frame.seq_num} with data: {frame.data}")

class Receiver:
    def __init__(self, window_size, seq_range):
        self.window_size = window_size
        self.seq_range = seq_range
        self.expected_seq = 0
        self.buffer = {}
        self.received = []

    def receive_frame(self, frame):
        if frame.seq_num in self.buffer or frame.seq_num < self.expected_seq:
            print(f"Receiver: Duplicate or out-of-window Frame {frame.seq_num} discarded")
            return None
        if self.expected_seq <= frame.seq_num < self.expected_seq + self.window_size:
            print(f"Receiver: Received Frame {frame.seq_num} with data: {frame.data}")
            self.buffer[frame.seq_num] = frame.data
            # Deliver in-order frames to upper layer
            while self.expected_seq in self.buffer:
                self.received.append(self.buffer[self.expected_seq])
                print(f"Receiver: Delivered Frame {self.expected_seq} to application")
                del self.buffer[self.expected_seq]
                self.expected_seq = (self.expected_seq + 1) % self.seq_range
            return frame.seq_num  # ACK
        else:
            print(f"Receiver: Frame {frame.seq_num} out of window, discarded")
            return None

# --- Simulation Parameters ---
WINDOW_SIZE = 4
SEQ_RANGE = 8     # Sequence numbers from 0 to 7 (modulo 8)
DATA_LIST = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
LOSS_PROBABILITY = 0.2    # Probability a frame or ACK is lost

# --- Initialize Sender and Receiver ---
sender = Sender(WINDOW_SIZE, SEQ_RANGE)
receiver = Receiver(WINDOW_SIZE, SEQ_RANGE)
sender.send_frames(DATA_LIST)

# --- Simulate Frame Sending and Receiving ---
while sender.window:
    acks_to_send = []
    for frame in list(sender.window):
        # Simulate frame loss
        if random.random() < LOSS_PROBABILITY:
            print(f"Frame {frame.seq_num} lost in transit!")
            continue
        ack = receiver.receive_frame(frame)
        if ack is not None:
            acks_to_send.append(ack)
    # Simulate ACK loss and sender reception
    for ack in acks_to_send:
        if random.random() < LOSS_PROBABILITY:
            print(f"ACK {ack} lost in transit!")
            continue
        sender.receive_ack(ack)
    # Simulate timeouts (retransmit unacknowledged frames)
    if sender.window and any(not f.acknowledged for f in sender.window):
        print("Timeout! Retransmitting lost frames...")
        sender.resend_lost_frames()
    print("-" * 45)
    time.sleep(1)  # Simulate a time step

print("\nAll frames delivered in order to receiver:", receiver.received)

SWP for selective Repeat
Working:
Sender transmits frames 1, 2, 3, 4.
Receiver gets 1, 3, 4:
    ACKs 1, 3, 4
    Buffers 3, 4 since 2 is missing.
Sender times out for 2:
    Retransmits 2.
Receiver gets 2:
    Delivers 1, 2, 3, 4 in order to upper layer
-------------------------------------------
Algorithm:
TX:
for each frame in window:
    send(frame)
    start_timer(frame)
while ACK not received for frame:
    if timer expired:
        retransmit(frame)
    else:
        move window forward on receiving ACK
RX:
if frame within window and not already received:
    buffer(frame)
    send_ack(frame)
    if all previous frames received:
        deliver_in_order()
else:
    discard(frame)
-----------------------------
# python code
import random
import time

class Frame:
    def __init__(self, seq_num, data):
        self.seq_num = seq_num
        self.data = data
        self.acknowledged = False

class Sender:
    def __init__(self, window_size, seq_range):
        self.window_size = window_size
        self.seq_range = seq_range
        self.base = 0
        self.next_seq = 0
        self.window = []

    def send_frames(self, data_list):
        # Fill window initially
        for data in data_list:
            if len(self.window) < self.window_size:
                self.window.append(Frame(self.next_seq, data))
                print(f"Sender: Sending Frame {self.next_seq} with data: {data}")
                self.next_seq = (self.next_seq + 1) % self.seq_range

    def receive_ack(self, ack_seq):
        print(f"Sender: Received ACK for Frame {ack_seq}")
        for frame in self.window:
            if frame.seq_num == ack_seq:
                frame.acknowledged = True
        # Slide window
        while self.window and self.window[0].acknowledged:
            self.window.pop(0)

    def resend_lost_frames(self):
        for frame in self.window:
            if not frame.acknowledged:
                print(f"Sender: Resending Frame {frame.seq_num} with data: {frame.data}")

class Receiver:
    def __init__(self, window_size, seq_range):
        self.window_size = window_size
        self.seq_range = seq_range
        self.expected_seq = 0
        self.buffer = {}
        self.received = []

    def receive_frame(self, frame):
        if frame.seq_num in self.buffer or frame.seq_num < self.expected_seq:
            print(f"Receiver: Duplicate or out-of-window Frame {frame.seq_num} discarded")
            return None
        if self.expected_seq <= frame.seq_num < self.expected_seq + self.window_size:
            print(f"Receiver: Received Frame {frame.seq_num} with data: {frame.data}")
            self.buffer[frame.seq_num] = frame.data
            # Deliver in-order frames to upper layer
            while self.expected_seq in self.buffer:
                self.received.append(self.buffer[self.expected_seq])
                print(f"Receiver: Delivered Frame {self.expected_seq} to application")
                del self.buffer[self.expected_seq]
                self.expected_seq = (self.expected_seq + 1) % self.seq_range
            return frame.seq_num  # ACK
        else:
            print(f"Receiver: Frame {frame.seq_num} out of window, discarded")
            return None

# --- Simulation Parameters ---
WINDOW_SIZE = 4
SEQ_RANGE = 8     # Sequence numbers from 0 to 7 (modulo 8)
DATA_LIST = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H']
LOSS_PROBABILITY = 0.2    # Probability a frame or ACK is lost

# --- Initialize Sender and Receiver ---
sender = Sender(WINDOW_SIZE, SEQ_RANGE)
receiver = Receiver(WINDOW_SIZE, SEQ_RANGE)
sender.send_frames(DATA_LIST)

# --- Simulate Frame Sending and Receiving ---
while sender.window:
    acks_to_send = []
    for frame in list(sender.window):
        # Simulate frame loss
        if random.random() < LOSS_PROBABILITY:
            print(f"Frame {frame.seq_num} lost in transit!")
            continue
        ack = receiver.receive_frame(frame)
        if ack is not None:
            acks_to_send.append(ack)
    # Simulate ACK loss and sender reception
    for ack in acks_to_send:
        if random.random() < LOSS_PROBABILITY:
            print(f"ACK {ack} lost in transit!")
            continue
        sender.receive_ack(ack)
    # Simulate timeouts (retransmit unacknowledged frames)
    if sender.window and any(not f.acknowledged for f in sender.window):
        print("Timeout! Retransmitting lost frames...")
        sender.resend_lost_frames()
    print("-" * 45)
    time.sleep(1)  # Simulate a time step

print("\nAll frames delivered in order to receiver:", receiver.received)


Stop and Wait

abcd

LeakyBucket Alg

abcd

Dijkstras

abcd

Distance Vector Routing

abcd

Broadcast Tree

abcd



Credits:
Andrew S. Tanenbaum - Computer Networks
Data-Communications-and-Network-5e- Behrouz-A.Forouzan