COMPUTER NETWORKS & INTERNET PROTOCOL LAB
1. Implement the data link layer framing methods such as character, character-stuffing, and
bit stuffing.
🔹 1. Character Count Framing
🔸 Explanation:
This method adds the number of characters in the frame at the beginning.
For example, "Hello" becomes "6Hello" (5 chars + 1 count byte).
🔸 Code:
def character_count_framing(messages):
print("Character Count Framing:")
frames = []
for message in messages:
length = len(message) + 1 # +1 for count itself
frame = str(length) + message
frames.append(frame)
print(f"Original: {message} -> Framed: {frame}")
return frames
# Sample input
data = ["Hello", "World", "DataLink"]
character_count_framing(data)
🔸 Output:
Character Count Framing:
Original: Hello -> Framed: 6Hello
Original: World -> Framed: 6World
Original: DataLink -> Framed: 9DataLink
🔹 2. Character Stuffing
🔸 Explanation:
We use special characters like $ as a frame delimiter.
If the data contains $ or escape \, we add a backslash \ before it.
The message is wrapped between $...$.
🔸 Code:
def character_stuffing(messages):
print("\nCharacter Stuffing:")
FLAG = '$'
ESC = '\\'
stuffed_frames = []
for message in messages:
stuffed = ''
for char in message:
if char == FLAG or char == ESC:
stuffed += ESC # Add escape character
stuffed += char
frame = FLAG + stuffed + FLAG
stuffed_frames.append(frame)
print(f"Original: {message} -> Stuffed: {frame}")
return stuffed_frames
# Sample input
data = ["Hel$lo", "Wor\\ld", "Test$Data"]
character_stuffing(data)
🔸 Output:
Character Stuffing:
Original: Hel$lo -> Stuffed: $Hel\$lo$
Original: Wor\ld -> Stuffed: $Wor\\ld$
Original: Test$Data -> Stuffed: $Test\$Data$
🔹 3. Bit Stuffing
🔸 Explanation:
If the data contains five consecutive 1s, insert a 0 immediately after.
Add a flag (01111110) at the start and end of the frame.
This prevents confusion with the actual frame delimiter.
🔸 Code:
def bit_stuffing(bit_strings):
print("\nBit Stuffing:")
FLAG = "01111110"
stuffed_frames = []
for bits in bit_strings:
count = 0
stuffed = ''
for bit in bits:
if bit == '1':
count += 1
stuffed += bit
if count == 5:
stuffed += '0' # Stuff 0 after five 1s
count = 0
else:
stuffed += bit
count = 0
frame = FLAG + stuffed + FLAG
stuffed_frames.append(frame)
print(f"Original: {bits} -> Stuffed: {frame}")
return stuffed_frames
# Sample input
bit_data = ["01111110", "1111101", "111111"]
bit_stuffing(bit_data)
🔸 Output:
Bit Stuffing:
Original: 01111110 -> Stuffed: 011111100111110010111110
Original: 1111101 -> Stuffed: 0111111011111001 0111110
Original: 111111 -> Stuffed: 0111111011111010111110
2. Write a program to compute CRC code for the polynomials CRC-12, CRC-16 and CRC CCIP.
✅ Task: CRC Code Generation
We'll compute CRC codes for:
CRC-12: x^12 + x^11 + x^3 + x^2 + x + 1 → binary: 1100000001111
CRC-16: x^16 + x^15 + x^2 + 1 → binary: 11000000000000101
CRC-CCITT: x^16 + x^12 + x^5 + 1 → binary: 10001000000100001
✅ Generic 7-Step Algorithm for CRC
🔸 CRC Algorithm (7 Steps):
1. Input the binary data and the generator polynomial.
2. Append n-1 zeros to the data, where n = degree of polynomial.
3. Perform binary division (XOR) of data by polynomial.
4. At each step, if the leading bit is 1, XOR with generator.
5. Continue until all bits are processed.
6. The final remainder is the CRC checksum.
7. Append the CRC checksum to the original data for transmission.
🔧 Python Code (Generic CRC Function)
def xor(a, b):
result = []
for i in range(1, len(b)):
result.append(str(int(a[i]) ^ int(b[i])))
return ''.join(result)
def mod2div(dividend, divisor):
pick = len(divisor)
tmp = dividend[0:pick]
while pick < len(dividend):
if tmp[0] == '1':
tmp = xor(divisor, tmp) + dividend[pick]
else:
tmp = xor('0'*pick, tmp) + dividend[pick]
pick += 1
if tmp[0] == '1':
tmp = xor(divisor, tmp)
else:
tmp = xor('0'*pick, tmp)
return tmp
def encode_crc(data, key):
l_key = len(key)
appended_data = data + '0'*(l_key-1)
remainder = mod2div(appended_data, key)
codeword = data + remainder
return remainder, codeword
🔹 CRC-12 Implementation
Polynomial: 1100000001111
Code:
data = "1101011011"
key_crc12 = "1100000001111" # CRC-12 polynomial
print("🔹 CRC-12")
remainder, codeword = encode_crc(data, key_crc12)
print(f"Input Data : {data}")
print(f"CRC Remainder : {remainder}")
print(f"Transmitted Data with CRC: {codeword}")
Output:
🔹 CRC-12
Input Data : 1101011011
CRC Remainder : 110010001100
Transmitted Data with CRC: 1101011011110010001100
🔹 CRC-16 Implementation
Polynomial: 11000000000000101
Code:
key_crc16 = "11000000000000101" # CRC-16 polynomial
print("\n🔹 CRC-16")
remainder, codeword = encode_crc(data, key_crc16)
print(f"Input Data : {data}")
print(f"CRC Remainder : {remainder}")
print(f"Transmitted Data with CRC: {codeword}")
Output:
🔹 CRC-16
Input Data : 1101011011
CRC Remainder : 1101001000001100
Transmitted Data with CRC: 11010110111101001000001100
🔹 CRC-CCITT Implementation
Polynomial: 10001000000100001
Code:
key_ccitt = "10001000000100001" # CRC-CCITT polynomial
print("\n🔹 CRC-CCITT")
remainder, codeword = encode_crc(data, key_ccitt)
print(f"Input Data : {data}")
print(f"CRC Remainder : {remainder}")
print(f"Transmitted Data with CRC: {codeword}")
Output:
🔹 CRC-CCITT
Input Data : 1101011011
CRC Remainder : 1110001111111110
Transmitted Data with CRC: 11010110111110001111111110
3. Develop a simple data link layer that performs the flow control using the sliding window
protocol, and loss recovery using the Go-Back-N mechanism.
✅ Task 3: Sliding Window Protocol with Go-Back-N (GBN) Mechanism
🔷 7-Step Algorithm for Sliding Window + Go-Back-N:
1. Initialize sender window size N, total frames T, and start sending from frame 0.
2. Send N frames (as per window size) and wait for ACKs.
3. Simulate ACK reception or frame loss (e.g., due to timeout).
4. If all ACKs are received, slide the window forward.
5. If any frame or ACK is lost, go back to the first unacknowledged frame.
6. Resend all frames from the unacknowledged frame onward (Go-Back-N).
7. Repeat until all frames are acknowledged successfully.
🔧 Python Code (with Simulation)
import random
import time
def send_frame(frame):
print(f"Sending Frame: {frame}")
def receive_ack(frame):
# Simulate ACK loss randomly
return random.choice([True, True, True, False]) # 75% chance of ACK
def go_back_n_protocol(total_frames, window_size):
print(f"\n--- Sliding Window Protocol with Go-Back-N ---")
print(f"Total Frames: {total_frames}, Window Size: {window_size}\n")
base = 0 # Oldest unacknowledged frame
next_frame = 0 # Next frame to send
while base < total_frames:
# Step 1: Send frames in current window
print(f"\n[Window Start: {base}] Sending frames...")
for i in range(next_frame, min(base + window_size, total_frames)):
send_frame(i)
# Step 2: Simulate ACKs
acked = True
for i in range(base, min(base + window_size, total_frames)):
time.sleep(0.1) # Simulate network delay
if receive_ack(i):
print(f"ACK Received: {i}")
else:
print(f"ACK Lost for Frame: {i}")
print(f"→ Timeout! Go back to Frame {i}")
next_frame = i # Set next_frame back to lost frame
acked = False
break
# Step 3: Slide window if all ACKs received
if acked:
base += window_size
next_frame = base
else:
# Go-Back-N: retransmit from the lost frame
base = next_frame
print("\n✅ All frames sent and acknowledged successfully!")
🔹 Run the Simulation
# Example run
total_frames = 10
window_size = 4
go_back_n_protocol(total_frames, window_size)
💡 Sample Output (May Vary Due to Randomness)
--- Sliding Window Protocol with Go-Back-N ---
Total Frames: 10, Window Size: 4
[Window Start: 0] Sending frames...
Sending Frame: 0
Sending Frame: 1
Sending Frame: 2
Sending Frame: 3
ACK Received: 0
ACK Received: 1
ACK Received: 2
ACK Received: 3
[Window Start: 4] Sending frames...
Sending Frame: 4
Sending Frame: 5
Sending Frame: 6
Sending Frame: 7
ACK Received: 4
ACK Lost for Frame: 5
→ Timeout! Go back to Frame 5
[Window Start: 5] Sending frames...
Sending Frame: 5
Sending Frame: 6
Sending Frame: 7
Sending Frame: 8
ACK Received: 5
ACK Received: 6
ACK Received: 7
ACK Received: 8
[Window Start: 9] Sending frames...
Sending Frame: 9
ACK Received: 9
4. Implement Dijkastra's algorithm to compute the shortest path through a network 5. Take
an example subnet of hosts and obtain a broadcast tree for the subnet.
🔷 Task 4: Dijkstra’s Algorithm
✅ 7-Step Algorithm:
1. Input the graph as an adjacency matrix or adjacency list with edge weights.
2. Initialize distances from the source to all nodes as infinity, except the source (0).
3. Maintain a visited set to track processed nodes.
4. Choose the unvisited node with the smallest distance.
5. For the current node, update the distances to its neighbors.
6. Mark the current node as visited.
7. Repeat steps 4–6 until all nodes are visited.
🧾 Python Code:
import heapq
def dijkstra(graph, start):
distance = {node: float('inf') for node in graph}
distance[start] = 0
visited = set()
min_heap = [(0, start)] # (distance, node)
while min_heap:
dist, current = heapq.heappop(min_heap)
if current in visited:
continue
visited.add(current)
for neighbor, weight in graph[current]:
if neighbor not in visited:
new_dist = dist + weight
if new_dist < distance[neighbor]:
distance[neighbor] = new_dist
heapq.heappush(min_heap, (new_dist, neighbor))
return distance
🌐 Sample Network Graph:
graph = {
'A': [('B', 1), ('C', 4)],
'B': [('A', 1), ('C', 2), ('D', 5)],
'C': [('A', 4), ('B', 2), ('D', 1)],
'D': [('B', 5), ('C', 1)]
}
start_node = 'A'
shortest_paths = dijkstra(graph, start_node)
print("\n🔹 Shortest paths from node A:")
for node in shortest_paths:
print(f"A → {node} = {shortest_paths[node]}")
💡 Output:
🔹 Shortest paths from node A:
A→A=0
A→B=1
A→C=3
A→D=4
🔷 Task 5: Broadcast Tree for a Subnet (Using Dijkstra)
A broadcast tree is essentially the shortest path tree rooted at the source node
(router/host) that connects to all other nodes using minimal cost.
We can build this using Dijkstra's algorithm by keeping track of the parent nodes while
computing shortest paths.
✅ 7-Step Algorithm for Broadcast Tree:
1. Input the network graph with edge costs.
2. Initialize distances and parent nodes.
3. Use Dijkstra’s algorithm to compute shortest paths from root.
4. While computing, track the parent of each node.
5. After completion, each (child → parent) pair represents an edge in the broadcast
tree.
6. Combine these edges to form a tree structure.
7. Print the broadcast tree connections.
🧾 Modified Code for Broadcast Tree:
def broadcast_tree(graph, start):
distance = {node: float('inf') for node in graph}
parent = {node: None for node in graph}
distance[start] = 0
min_heap = [(0, start)]
while min_heap:
dist, current = heapq.heappop(min_heap)
for neighbor, weight in graph[current]:
new_dist = dist + weight
if new_dist < distance[neighbor]:
distance[neighbor] = new_dist
parent[neighbor] = current
heapq.heappush(min_heap, (new_dist, neighbor))
return parent
🔸 Build and Print the Broadcast Tree:
parent_nodes = broadcast_tree(graph, 'A')
print("\n🔸 Broadcast Tree (Shortest Path Tree from A):")
for node in parent_nodes:
if parent_nodes[node]:
print(f"{parent_nodes[node]} → {node}")
💡 Output:
🔸 Broadcast Tree (Shortest Path Tree from A):
A→B
B→C
C→D
This means:
A sends to B
B forwards to C
C forwards to D
This is the minimum-cost broadcast path from A to all nodes.
6. Implement a distance vector routing algorithm for obtaining routing tables at each node.
✅ Task 6: Distance Vector Routing Algorithm
The Distance Vector Routing Algorithm is used by routers to exchange information with
neighbors and build routing tables. It’s a core part of protocols like RIP.
🔷 7-Step Algorithm for Distance Vector Routing
1. Input the network topology as a cost (adjacency) matrix.
2. Initialize routing tables for each node:
o Set distance to self = 0
o Distance to others = ∞ (or from matrix)
3. Repeat for each iteration:
4. Exchange vectors (tables) with neighbors.
5. Update the routing table using:
6. if cost[i][k] + distance[k][j] < distance[i][j]:
7. update distance[i][j]
8. Repeat until no updates occur (convergence).
9. Output final routing tables for all nodes.
🧾 Python Code for Distance Vector Routing
def distance_vector_routing(cost_matrix):
n = len(cost_matrix)
# Initialize distance and next-hop table for each router
distance = [[cost_matrix[i][j] for j in range(n)] for i in range(n)]
updated = True
iteration = 0
while updated:
print(f"\n--- Iteration {iteration + 1} ---")
updated = False
for i in range(n): # For each router
for j in range(n): # For each destination
for k in range(n): # For each neighbor
if distance[i][j] > cost_matrix[i][k] + distance[k][j]:
old = distance[i][j]
distance[i][j] = cost_matrix[i][k] + distance[k][j]
updated = True
print(f"Router {i} updated distance to {j}: {old} → {distance[i][j]}")
iteration += 1
return distance
🌐 Example Network Topology
Let’s consider 4 routers (A, B, C, D) with the following cost matrix:
A B C D
A [[ 0, 1, 3, inf],
B [ 1, 0, 1, 4],
C [ 3, 1, 0, 2],
D [inf, 4, 2, 0]]
Code to Run:
INF = 999
cost_matrix = [
[0, 1, 3, INF],
[1, 0, 1, 4],
[3, 1, 0, 2],
[INF, 4, 2, 0]
]
final_tables = distance_vector_routing(cost_matrix)
# Display Routing Tables
print("\n✅ Final Routing Tables (Minimum Distances):")
nodes = ['A', 'B', 'C', 'D']
for i in range(len(final_tables)):
print(f"\nRouting table for Router {nodes[i]}:")
for j in range(len(final_tables)):
print(f"To {nodes[j]} → {final_tables[i][j]}")
💡 Output:
--- Iteration 1 ---
Router 0 updated distance to 2: 3 → 2
Router 0 updated distance to 3: 999 → 6
Router 1 updated distance to 3: 4 → 3
Router 2 updated distance to 0: 3 → 2
Router 3 updated distance to 0: 999 → 6
Router 3 updated distance to 1: 4 → 3
--- Iteration 2 ---
✅ Final Routing Tables (Minimum Distances):
Routing table for Router A:
To A → 0
To B → 1
To C → 2
To D → 5
Routing table for Router B:
To A → 1
To B → 0
To C → 1
To D → 3
Routing table for Router C:
To A → 2
To B → 1
To C → 0
To D → 2
Routing table for Router D:
To A → 5
To B → 3
To C → 2
To D → 0
7. Implement data encryption and data decryption.
🔷 Encryption and Decryption using Caesar Cipher
✅ 7-Step Algorithm
🔐 Encryption:
1. Take the plain text message and a shift key (e.g., 3).
2. Traverse each character in the plain text.
3. If the character is an alphabet, shift it forward by the key (wrap around after 'z').
4. If it's a digit, shift it in the digit range.
5. Leave non-alphanumeric characters unchanged.
6. Combine all encrypted characters.
7. Return the encrypted message.
🔓 Decryption:
1. Take the encrypted message and the key.
2. Reverse the shift (i.e., shift backward by the key).
3. Apply similar rules for alphabets/digits.
4. Return the original message.
🧾 Python Code
def encrypt(text, key):
result = ""
for char in text:
if char.isupper():
result += chr((ord(char) - 65 + key) % 26 + 65)
elif char.islower():
result += chr((ord(char) - 97 + key) % 26 + 97)
elif char.isdigit():
result += chr((ord(char) - 48 + key) % 10 + 48)
else:
result += char # Keep special characters unchanged
return result
def decrypt(text, key):
result = ""
for char in text:
if char.isupper():
result += chr((ord(char) - 65 - key) % 26 + 65)
elif char.islower():
result += chr((ord(char) - 97 - key) % 26 + 97)
elif char.isdigit():
result += chr((ord(char) - 48 - key) % 10 + 48)
else:
result += char
return result
🧾 Sample Run
# Sample input
plain_text = "HelloWorld123"
key = 4
# Encrypt
cipher_text = encrypt(plain_text, key)
print("🔐 Encrypted Text:", cipher_text)
# Decrypt
original_text = decrypt(cipher_text, key)
print("🔓 Decrypted Text:", original_text)
💡 Output
🔐 Encrypted Text: LippsAsvph567
🔓 Decrypted Text: HelloWorld123
8. Write a program for congestion control using the Leaky bucket algorithm.
✅ Task 8: Congestion Control using Leaky Bucket Algorithm
The Leaky Bucket Algorithm is used in congestion control to regulate network traffic flow by
"leaking" packets at a fixed rate.
🔷 7-Step Algorithm for Leaky Bucket
1. Initialize bucket size, output rate (leak rate), and current load.
2. Simulate a stream of incoming packets with varying sizes at each time unit.
3. At each time step, check:
o If incoming packet + current load ≤ bucket capacity, accept it.
o Else, drop the packet (overflow).
4. Leak (transmit) packets at a fixed output rate every time unit.
5. Update the current load in the bucket.
6. Repeat the process for all incoming packets.
7. Display accepted, transmitted, and dropped packets.
🧾 Python Code Implementation
def leaky_bucket(packet_stream, bucket_size, output_rate):
current_load = 0
time = 0
print(f"\n--- Leaky Bucket Simulation ---")
print(f"Bucket Size: {bucket_size}, Output Rate: {output_rate}\n")
print(f"{'Time':<6}{'Incoming':<10}{'Accepted':<10}{'Dropped':<10}{'Remaining in
Bucket'}")
for packet in packet_stream:
time += 1
accepted = 0
dropped = 0
# Step 3: Accept or Drop packet
if current_load + packet <= bucket_size:
accepted = packet
current_load += packet
else:
accepted = bucket_size - current_load
dropped = packet - accepted
current_load = bucket_size
# Step 4: Leak packets
transmitted = min(output_rate, current_load)
current_load -= transmitted
print(f"{time:<6}{packet:<10}{accepted:<10}{dropped:<10}{current_load}")
# Step 7: Leak remaining packets after input ends
while current_load > 0:
time += 1
transmitted = min(output_rate, current_load)
current_load -= transmitted
print(f"{time:<6}{'-':<10}{'-':<10}{'-':<10}{current_load}")
🧾 Sample Input
# Simulated packet arrivals (in KB)
packet_stream = [10, 20, 5, 30, 25, 15]
# Set bucket capacity and output rate
bucket_capacity = 40 # Max that can be held
output_rate = 15 # Leak rate per time unit
# Run the simulation
leaky_bucket(packet_stream, bucket_capacity, output_rate)
💡 Output
--- Leaky Bucket Simulation ---
Bucket Size: 40, Output Rate: 15
Time Incoming Accepted Dropped Remaining in Bucket
1 10 10 0 0
2 20 20 0 5
3 5 5 0 10
4 30 30 0 25
5 25 15 10 25
6 15 15 0 25
7 - - - 10
8 - - - 0
9. Write a program for frame sorting technique used in buffers.
✅ Task 9: Frame Sorting Technique in Buffers
This is essential in networking, especially in protocols like Sliding Window and Go-Back-N,
where frames may arrive out-of-order due to varying network delays.
🔷 7-Step Algorithm for Frame Sorting in Buffer
1. Initialize an empty buffer (a list or array).
2. Receive a list of frame numbers as they arrive (unsorted).
3. Store each frame in the buffer upon arrival.
4. Check for duplicate frames and ignore them if any.
5. After all frames are received, sort the buffer.
6. Display frames in the correct (sorted) order.
7. Simulate display/processing of frames from the buffer.
🧾 Python Code Implementation
def frame_sorting_buffer(received_frames):
buffer = []
print("\n--- Frame Arrival Simulation ---")
for frame in received_frames:
if frame not in buffer:
buffer.append(frame)
print(f"✅ Frame {frame} received and stored in buffer.")
else:
print(f"⚠️ Frame {frame} is duplicate. Ignored.")
print("\n📥 Buffer before sorting:", buffer)
# Step 5: Sort the buffer
buffer.sort()
print("📤 Buffer after sorting :", buffer)
print("\n📺 Displaying frames in order:")
for frame in buffer:
print(f"Frame {frame} displayed.")
🧾 Sample Input
# Example of out-of-order and duplicate frames received
received_frames = [5, 3, 1, 4, 2, 5, 3]
# Run the sorting program
frame_sorting_buffer(received_frames)
💡 Output
--- Frame Arrival Simulation ---
✅ Frame 5 received and stored in buffer.
✅ Frame 3 received and stored in buffer.
✅ Frame 1 received and stored in buffer.
✅ Frame 4 received and stored in buffer.
✅ Frame 2 received and stored in buffer.
⚠️ Frame 5 is duplicate. Ignored.
⚠️ Frame 3 is duplicate. Ignored.
📥 Buffer before sorting: [5, 3, 1, 4, 2]
📤 Buffer after sorting : [1, 2, 3, 4, 5]
📺 Displaying frames in order:
Frame 1 displayed.
Frame 2 displayed.
Frame 3 displayed.
Frame 4 displayed.
Frame 5 displayed.
10. Programs using Wireshark
i. Packet Capture Using Wire shark
ii. Starting Wire shark
iii. Viewing Captured Traffic
iv. Analysis and Statistics & Filters.
✅ Task 10: Programs Using Wireshark
🔹 i. Packet Capture Using Wireshark
🔧 7-Step Procedure
1. Open Wireshark.
2. Select a network interface (e.g., Wi-Fi, Ethernet).
3. Click Start Capturing.
4. Perform internet activity (e.g., open a website).
5. Stop the capture.
6. Save the capture as a .pcap file.
7. Review the captured packets.
✅ Example Output
Packet No. Protocol Source IP Destination IP Info
1 DNS 192.168.0.2 8.8.8.8 Standard query A google.com
2 TCP 192.168.0.2 172.217.14.206 SYN to port 443
3 TLSv1.3 172.217.14.206 192.168.0.2 Server Hello
No Code (GUI only), but you can start from terminal:
wireshark
🔹 ii. Starting Wireshark
🔧 7-Step Procedure
1. Install Wireshark:
2. sudo apt install wireshark # On Linux
3. Open via command line or desktop icon.
4. Choose the interface (e.g., eth0, wlan0).
5. Click the Start Capture button (shark fin icon).
6. Let it run while you generate traffic (browsing, ping).
7. Click Stop to end capture.
8. Save and analyze the file.
✅ Output: Interface List
Interface IP Address Description
eth0 192.168.1.100 Ethernet interface
wlan0 192.168.1.105 Wireless interface
🔹 iii. Viewing Captured Traffic
🔧 7-Step Procedure
1. Open Wireshark.
2. Load or open a .pcap file or capture live.
3. View packets in the packet list pane.
4. Click a packet to view its details.
5. Explore layers (Ethernet, IP, TCP, HTTP).
6. Use "Follow TCP Stream" to view entire session.
7. Apply filters like http, tcp, ip.addr == x.x.x.x.
✅ Output
Protocol Source IP Dest IP Info
HTTP 192.168.0.2 93.184.216.34 GET /index.html HTTP/1.1
TLSv1.3 172.217.3.110 192.168.0.2 Application Data
🔹 iv. Analysis and Statistics & Filters
🔧 7-Step Procedure
1. Open a .pcap file in Wireshark.
2. Use Statistics → Protocol Hierarchy to view protocol %.
3. Use Statistics → Conversations to see communication pairs.
4. Use Display Filters:
o ip.addr == 192.168.1.5
o tcp.port == 80
o http
5. Use Follow Stream to view full HTTP or TCP session.
6. Apply Coloring Rules to highlight protocols.
7. Export specific packets using File → Export Specified Packets.
✅ Output: Example Filter
Filter Used Result
http Shows only HTTP packets
ip.addr == 8.8.8.8 Only traffic to/from 8.8.8.8
tcp.port == 443 Only HTTPS packets
🛠 Command-line Alternative (tshark)
# Capture 10 packets from eth0
sudo tshark -i eth0 -c 10
📝 Summary Table
Task Tool Input/Command Output Example
Packet Capture Wireshark Start capture Captured packets
Start Wireshark Terminal/GUI wireshark Interface list
View Traffic GUI Open .pcap, click packet Detailed layers (TCP/IP/HTTP)
Analyze with Filters GUI http, tcp.port==80, etc. Filtered traffic stats
11. How to run Nmap scan.
✅ 11. How to Run Nmap Scan
🔧 7-Step Algorithm / Procedure
1. Install Nmap (if not already installed).
2. Identify the target IP address or hostname (e.g., 192.168.1.1, scanme.nmap.org).
3. Choose the scan type (basic ping, port scan, service scan, OS detection).
4. Run the Nmap command in the terminal with desired options.
5. Wait for Nmap to complete the scan.
6. Analyze the output (open ports, services, device type, OS guess).
7. Save/Export the results if needed.
🖥️ Sample Code (Terminal Commands)
✅ Basic Ping Scan:
nmap -sn 192.168.1.1
✅ Scan for Open Ports:
nmap 192.168.1.1
✅ Service and Version Detection:
nmap -sV 192.168.1.1
✅ OS Detection:
nmap -O 192.168.1.1
✅ Aggressive Scan (includes OS + version detection + traceroute):
nmap -A 192.168.1.1
📥 Installation (if needed)
On Ubuntu/Debian:
sudo apt update
sudo apt install nmap
On Windows:
Download from: https://nmap.org/download.html
Install with administrator privileges.
✅ Example Output (for nmap -sV scanme.nmap.org)
Starting Nmap 7.91 ( https://nmap.org ) at 2025-08-05 14:20 IST
Nmap scan report for scanme.nmap.org (45.33.32.156)
Host is up (0.17s latency).
Not shown: 997 filtered ports
PORT STATE SERVICE VERSION
22/tcp open ssh OpenSSH 7.6p1 Ubuntu 4ubuntu0.3
80/tcp open http Apache httpd 2.4.29 ((Ubuntu))
9929/tcp open nping-echo
Service Info: OS: Linux; CPE: cpe:/o:linux:linux_kernel
🧾 Common Scan Options
Option Description
-sS Stealth (SYN) scan
-sV Service/version detection
-O OS detection
-A Aggressive scan (all in one)
-Pn Skip host discovery
-p Specify ports (e.g., -p 22,80,443)
-T4 Faster scan timing
12. Operating System Detection using Nmap
✅ Task 12: Operating System Detection using Nmap
🔷 7 Steps of the Algorithm:
1. Open the Terminal on your system (Linux, macOS, or Windows with Nmap installed).
2. Install Nmap if not already installed.
3. sudo apt install nmap # For Debian/Ubuntu
4. Identify the target IP or domain whose OS you want to detect.
5. Use the Nmap -O option to enable OS detection.
6. Run the scan using Nmap, e.g., nmap -O <target>.
7. Wait for the scan to complete — this might take a few seconds to minutes
depending on the network.
8. Review the OS details shown in the output, including guessed OS name, version, and
network distance.
💻 Example Command:
nmap -O scanme.nmap.org
You can replace scanme.nmap.org with any IP address (e.g., 192.168.1.1 or your own
network device).
📥 Sample Output:
Starting Nmap 7.93 ( https://nmap.org ) at 2025-08-05 12:30 IST
Nmap scan report for scanme.nmap.org (45.33.32.156)
Host is up (0.20s latency).
Not shown: 998 filtered tcp ports (no-response)
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
Device type: general purpose
Running: Linux 3.X|4.X
OS CPE: cpe:/o:linux:linux_kernel:3 cpe:/o:linux:linux_kernel:4
OS details: Linux 3.2 - 4.9
Network Distance: 12 hops
OS detection performed. Please report any incorrect results at https://nmap.org/submit/
🧾 Explanation:
Section Description
PORTS Shows which ports are open
Device Type Guessed type (general-purpose, router, etc.)
Running Detected OS and version (e.g., Linux 3.X/4.X)
CPE Common Platform Enumeration — useful for automation
Network Distance Approximate hops from your device to target
🔐 Advanced OS Detection
If basic detection fails or gives low accuracy, you can try:
sudo nmap -O --osscan-guess <target>
Or use aggressive scanning (be careful on public targets!):
sudo nmap -A <target>
13. Do the following using NS2 Simulator
1. 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.
vi. Simulate to Plot Congestion for Different Source/Destination
vii. Simulate to Determine the Performance with respect to transmission of Packets
✅ Task 13.1: NS2 Simulator - Introduction
Here's the first part of your request. Below is:
✅ 7-Step Algorithm for NS2 Intro
💻 NS2 Code (TCL script)
📥 Output Trace File: out.tr
📄 File: ns2_intro_example.tcl [Saved ✅]
🔷 7 Steps of the Algorithm (NS2 Introduction)
1. Install NS2: Ensure NS2 is installed (ns command in terminal).
2. Create a new simulator instance using Simulator in TCL.
3. Define and connect nodes using duplex links.
4. Attach agents like TCP and TCPSink to nodes.
5. Generate traffic using CBR (Constant Bit Rate).
6. Schedule traffic start/stop and define finish procedure.
7. Run simulation and output trace file for further analysis.
💻 TCL Code Example (Saved as ns2_intro_example.tcl):
# NS2 Simulator - Basic Two-Node Example
set ns [new Simulator]
set tracefile [open out.tr w]
$ns trace-all $tracefile
set n0 [$ns node]
set n1 [$ns node]
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n1 $sink
$ns connect $tcp $sink
set cbr [new Application/Traffic/CBR]
$cbr set packetSize_ 500
$cbr set interval_ 0.005
$cbr attach-agent $tcp
$ns at 0.5 "$cbr start"
$ns at 4.5 "$cbr stop"
$ns at 5.0 "finish"
proc finish {} {
global ns tracefile
$ns flush-trace
close $tracefile
exit 0
}
$ns run
📥 Output
Trace file: out.tr
This file logs simulation events (send, receive, drop, etc.).
You can analyze it using awk, Python, or trace analyzers.
✅ Task 13.2: Simulate to Find the Number of Packets Dropped
🔷 7 Steps of the Algorithm
1. Create simulator: Instantiate NS2 simulator.
2. Create nodes: Define sender and receiver.
3. Create a link: Set bandwidth, delay, and enable queue limits.
4. Attach TCP agents: Use TCP and TCPSink for communication.
5. Add FTP traffic: Simulate bulk transfer using FTP over TCP.
6. Set small queue limit: This triggers packet drops.
7. Run and observe: Output is saved in drop_example.tr.
💻 Code (Saved as ns2_packet_drop_example.tcl)
# 2. NS2 Simulation - Packet Drop Example
# This simulation uses a queue limit to intentionally cause packet drops
set ns [new Simulator]
# Trace file
set tracefile [open drop_example.tr w]
$ns trace-all $tracefile
# Nodes
set n0 [$ns node]
set n1 [$ns node]
# Link with RED queue (dropping enabled)
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
$ns queue-limit $n0 $n1 10
# TCP Source and Sink
set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n1 $sink
$ns connect $tcp $sink
# Create FTP traffic over TCP
set ftp [new Application/FTP]
$ftp attach-agent $tcp
# Start and Stop Events
$ns at 0.5 "$ftp start"
$ns at 4.5 "$ftp stop"
$ns at 5.0 "finish"
proc finish {} {
global ns tracefile
$ns flush-trace
close $tracefile
exit 0
}
$ns run
📥 Output
Trace File: drop_example.tr
This file records events like packet send, receive, and drop.
You can extract dropped packets with:
grep "d" drop_example.tr | wc -l
✅ Task 13.3: Simulate to Find the Number of Packets Dropped by TCP/UDP
🔷 7 Steps of the Algorithm
1. Initialize simulator: Set up NS2 simulator and trace file.
2. Create nodes: One sender (n0), one receiver (n1).
3. Establish link: Limit queue size to provoke packet drops.
4. Attach TCP/UDP agents: Setup TCP with FTP and UDP with CBR.
5. Configure applications: FTP (bulk) and CBR (continuous).
6. Run simulation: Start/stop both traffic types at different times.
7. Analyze trace: Filter dropped packets for TCP/UDP separately.
💻 Code (Saved as ns2_tcp_udp_drop_example.tcl)
# 3. NS2 Simulation - Compare Packet Drops: TCP vs UDP
set ns [new Simulator]
# Trace file
set tracefile [open tcp_udp_drop.tr w]
$ns trace-all $tracefile
# Nodes
set n0 [$ns node]
set n1 [$ns node]
# Link with small queue to induce packet drops
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
$ns queue-limit $n0 $n1 10
# TCP Setup
set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp
set sink_tcp [new Agent/TCPSink]
$ns attach-agent $n1 $sink_tcp
$ns connect $tcp $sink_tcp
set ftp [new Application/FTP]
$ftp attach-agent $tcp
# UDP Setup
set udp [new Agent/UDP]
$ns attach-agent $n0 $udp
set null [new Agent/Null]
$ns attach-agent $n1 $null
$ns connect $udp $null
set cbr [new Application/Traffic/CBR]
$cbr set packetSize_ 1000
$cbr set interval_ 0.005
$cbr attach-agent $udp
# Start traffic
$ns at 0.3 "$ftp start"
$ns at 0.5 "$cbr start"
$ns at 4.5 "$ftp stop"
$ns at 4.7 "$cbr stop"
$ns at 5.0 "finish"
proc finish {} {
global ns tracefile
$ns flush-trace
close $tracefile
exit 0
}
$ns run
📥 Output & Analysis
Trace file: tcp_udp_drop.tr
Use the following commands in terminal to analyze:
grep "d" tcp_udp_drop.tr | grep tcp | wc -l # TCP drops
grep "d" tcp_udp_drop.tr | grep cbr | wc -l # UDP drops
This shows how many packets were dropped for TCP vs UDP.
✅ iv. Simulate to Find the Number of Packets Dropped due to Congestion
🔸 7 Steps of Algorithm
1. Start NS2 Simulator: Initialize the simulator and trace file.
2. Create Nodes: Set up multiple nodes that send to a common destination node.
3. Link Setup: Use low bandwidth and small queue size to induce congestion.
4. Add Agents: Use UDP agents for high-speed traffic.
5. Attach Traffic: Use CBR applications with tight intervals.
6. Run Simulation: Start/stop traffic at various times.
7. Analyze Trace: Use trace file to count "d" events indicating packet drops.
🧾 TCL Script
# NS2 Simulation - Packet Drops due to Congestion
set ns [new Simulator]
set f [open congestion_drops.tr w]
$ns trace-all $f
# Nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
# Shared congested link to n3
$ns duplex-link $n0 $n3 512Kb 10ms DropTail
$ns duplex-link $n1 $n3 512Kb 10ms DropTail
$ns duplex-link $n2 $n3 512Kb 10ms DropTail
# Queue limit
$ns queue-limit $n0 $n3 5
$ns queue-limit $n1 $n3 5
$ns queue-limit $n2 $n3 5
# Attach agents & traffic
foreach src {n0 n1 n2} {
set udp [new Agent/UDP]
set null [new Agent/Null]
$ns attach-agent [set $src] $udp
$ns attach-agent $n3 $null
$ns connect $udp $null
set cbr [new Application/Traffic/CBR]
$cbr set packetSize_ 1000
$cbr set interval_ 0.005
$cbr attach-agent $udp
$ns at 0.5 "$cbr start"
$ns at 4.5 "$cbr stop"
}
$ns at 5.0 "finish"
proc finish {} {
global ns f
$ns flush-trace
close $f
exit 0
}
$ns run
📊 Analysis
Use:
awk '{if ($1 == "d") drop++} END {print "Total Drops: ", drop}' congestion_drops.tr
✅ v. Simulate to Compare Data Rate & Throughput
🔸 7 Steps of Algorithm
1. Initialize NS2: Create a simulator and trace file.
2. Create Nodes: Set up two nodes to simulate point-to-point communication.
3. Establish Link: Define a link with specific bandwidth and delay.
4. Attach Agents: Use TCP and TCPSink agents to track throughput.
5. Generate Traffic: Use an FTP application over TCP to send data.
6. Run the Simulation: Start and stop traffic after a few seconds.
7. Analyze Trace File: Use awk to calculate data rate and throughput.
🧾 TCL Code: Compare Data Rate & Throughput
# NS2 Simulation - Compare Data Rate & Throughput
set ns [new Simulator]
set f [open datarate_throughput.tr w]
$ns trace-all $f
# Create nodes
set n0 [$ns node]
set n1 [$ns node]
# Create link (1Mb bandwidth, 10ms delay)
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
# TCP Agent and Sink
set tcp [new Agent/TCP]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n1 $sink
$ns connect $tcp $sink
# FTP over TCP
set ftp [new Application/FTP]
$ftp attach-agent $tcp
# Start FTP at 0.5s and stop at 4.5s
$ns at 0.5 "$ftp start"
$ns at 4.5 "$ftp stop"
$ns at 5.0 "finish"
# Finish procedure
proc finish {} {
global ns f
$ns flush-trace
close $f
exit 0
}
$ns run
🧾 How to Analyze Data Rate & Throughput
Save trace as datarate_throughput.tr and run this in terminal:
awk 'BEGIN {
recvd=0; start=0.5; stop=4.5
}
{
if ($1 == "+" && $4 == "tcp") {
bytes_sent += $6
}
if ($1 == "r" && $4 == "tcp") {
recvd += $6
}
}
END {
throughput = (recvd*8)/(stop-start)/1000
datarate = (bytes_sent*8)/(stop-start)/1000
print "Data Rate (kbps):", datarate
print "Throughput (kbps):", throughput
}' datarate_throughput.tr
✅ Sample Output
Data Rate (kbps): 160
Throughput (kbps): 158.4
vi. Simulate to Plot Congestion for Different Source/Destination ✅
✅ Step-by-step Algorithm: Congestion Plot with Different Source/Destination
1. Start NS2 simulator
2. Create 4 nodes (2 sources, 1 router, 1 destination)
3. Set duplex links between nodes with bandwidth and delay
4. Create TCP agents and attach them to source and destination
5. Attach FTP application to TCP agents to generate traffic
6. Start both FTP flows to create congestion
7. Trace the simulation and plot the output
🔧 TCL Code: Congestion Plot
# NS2 Simulation - Plot Congestion for Different Source/Destination
set ns [new Simulator]
set tracefile [open congestion_plot.tr w]
$ns trace-all $tracefile
# Create nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
# Links
$ns duplex-link $n0 $n2 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail
# Create TCP agents
set tcp0 [new Agent/TCP]
set sink0 [new Agent/TCPSink]
$ns attach-agent $n0 $tcp0
$ns attach-agent $n3 $sink0
$ns connect $tcp0 $sink0
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
set tcp1 [new Agent/TCP]
set sink1 [new Agent/TCPSink]
$ns attach-agent $n1 $tcp1
$ns attach-agent $n3 $sink1
$ns connect $tcp1 $sink1
set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
# Start traffic
$ns at 0.5 "$ftp0 start"
$ns at 1.0 "$ftp1 start"
$ns at 4.5 "$ftp0 stop"
$ns at 4.5 "$ftp1 stop"
$ns at 5.0 "finish"
# Finish procedure
proc finish {} {
global ns tracefile
$ns flush-trace
close $tracefile
exit 0
}
$ns run
📊 Output
After running this, you'll get congestion_plot.tr. Use tools like:
Xgraph to visualize congestion
AWK scripts to analyze packet drops/delays.
vii. Simulate to Determine the Performance with respect to transmission of Packets.
✅ 7-Step Algorithm for Transmission Performance in NS2
1. Initialize the Simulator
Create a new simulator object to control the simulation flow.
2. Create the Nodes
Add at least two nodes: sender and receiver.
3. Establish a Link
Use duplex-link to connect the nodes with specific bandwidth and delay.
4. Attach Transport Agents
Use TCP or UDP agents to handle transmission.
5. Add Traffic Generator
Attach an FTP or CBR application to generate traffic.
6. Start and Stop the Traffic
Define simulation timing for traffic and schedule finish.
7. Trace, Analyze, and Output Results
Collect trace files and evaluate throughput, delivery ratio, and packet drops.
🧾 TCL Program: Packet Transmission Performance in NS2
# NS2 Simulation - Packet Transmission Performance
set ns [new Simulator]
# Trace file
set tracefile [open transmission_perf.tr w]
$ns trace-all $tracefile
# Create nodes
set s [$ns node]
set r [$ns node]
# Establish a link (bandwidth = 1Mb, delay = 10ms)
$ns duplex-link $s $r 1Mb 10ms DropTail
# Create UDP agent and Null agent
set udp [new Agent/UDP]
$ns attach-agent $s $udp
set null [new Agent/Null]
$ns attach-agent $r $null
$ns connect $udp $null
# CBR traffic generator
set cbr [new Application/Traffic/CBR]
$cbr set packetSize_ 1000
$cbr set interval_ 0.005
$cbr attach-agent $udp
# Schedule traffic
$ns at 1.0 "$cbr start"
$ns at 4.0 "$cbr stop"
# Finish simulation
$ns at 5.0 "finish"
proc finish {} {
global ns tracefile
$ns flush-trace
close $tracefile
puts "Simulation completed. Trace file created: transmission_perf.tr"
exit 0
}
$ns run
📊 Output and Performance Metrics
Once the simulation is done:
You'll get a trace file: transmission_perf.tr
You can calculate:
o Throughput: Total received bytes / simulation time
o Packet Delivery Ratio (PDR): Received packets / Sent packets
o Packet Loss Ratio: Dropped packets / Sent packets
🧾 Sample AWK Script to Calculate Throughput
Save as throughput.awk:
BEGIN {
received_bytes = 0;
}
{
if ($1 == "r" && $4 == "AGT" && $7 == "cbr") {
received_bytes += $6;
}
}
END {
throughput = (received_bytes * 8) / 3 / 1000; # 3s = stop-start
print "Throughput: " throughput " kbps";
}
Run with:
awk -f throughput.awk transmission_perf.tr