Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
13 views44 pages

CN Lab Manual

Uploaded by

fakefakke0001
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)
13 views44 pages

CN Lab Manual

Uploaded by

fakefakke0001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 44

Lab Manual

Course : computer networks Lab

Course code : 23CS504

Year& Semester : III B.Tech I semester

Regulation : NR23

DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING

NARASIMHA REDDY ENGINEERING COLLEGE

Approved by AICTE, New Delhi, Accredited by NAAC&NBA, Affiliated to


JNTUH, Maisammaguda kompally,Secunderabad-500100,Telangana
1.Institute Vision & Mission
Vision of the Institute

To produce competent professionals who can contribute to the industry, researchand


societal benefits with environment consciousness and ethical Values.

Mission of the Institute

M1: Adapt continuous improvements in innovative teaching-learning practices and state-of-


the- art infrastructure to transform students as competent professionals and entrepreneurs in
multi-disciplinary fields.

M2: Develop an innovative ecosystem with strong involvement and participation of students
and faculty members.

M3: Impart National development spirit among the students to utilize their knowledge and
skills for societal benefits with ethical values.

Vision of the Department:

To produce technically competent professionals with quality education in cutting edge


technologies with professional ethics.

Mission of the Department:

M1: To impart quality technical education in design and implementation of IT applications through
innovative teaching - learning practices

M2:To in culcate Professional behavior, with strong ethical values, and research capabilities.

M3:To educate students to be effective problem solvers with social sensitivity for the betterment of
the society and humanity as a whole.

Programme Educational Objectives(PEOs):

PEO-I:To provide students with a solid foundation in mathematics, engineering, basic science
fundamentals required to solve computing problems and also to pursue higher studies and
research.

PEO-II: To train students with good Computer Science and Engineering breadth so as to
comprehend, analyze, design and create innovative computing products and solutions for real
lifeproblems.

PEO-III: To inculcate in students professional and ethical attitude, communication skills,


teamwork skills, multi-disciplinary approach and an ability to relate computer engineering
issues with social awareness.
PROGRAMOUTCOMES(POs):
PO1.Engineering knowledge: Apply the knowledge of basic sciences and
1
Fundamental engineering concepts in solving engineering problems.
PO2. Problem analysis: Identify and define engineering problems, conduct
2 experiments and investigate to analyze and interpret data to arrive at sub stantial
conclusions.
PO3.Design/development of solutions: Propose an appropriate solution for
3 engineering problems complying with functional constraints such as economic,
environmental, societal, ethical, safety and sustainability.
PO4.Conduct investigations of complex problems: Perform investigations,
4 Design and conduct experiments, analyze and interpret the results to provide valid
conclusions.
PO5.Modern tool usage: Selector create and apply appropriate techniques and
5
IT tools for the design & analysis of the systems.
PO6.The engineer and society: Apply reasoning informed by the contextual
6 Knowledge to assess societal, health, safety, legal and cultural issues and the
consequentresponsibilitiesrelevanttotheprofessionalengineeringpractice.
PO7.Environment and sustainability: Demonstrate professional skills and
7 Contextual reasoning to assess environmental or societal issues for sustainable
development.
PO8.Ethics: Apply ethical principles and commit to professional ethics and
8
Responsibilities and norms of the engineering practice.
PO9.Individual and teamwork: Function effectively as an individual,and asa
9
Member or leader in diverse teams, and in multi-disciplinary situations.
PO10. Communication: Communicate effectively among engineering
10 Community, being able to comprehend and write effectively
reports, presentation and give / receive clears instructions.
PO11.Projectmanagementandfinance: Demonstrate and apply engineering &
11 management principles in their own / team projects in multidisciplinary
environment.
PO12.Life-longlearning: Recognize the need for, and have the ability to Engage in
12
independent and lifelong learning.

PROGRAM SPECIFIC OUTCOMES (PSOs):


PSO1: To provide effective and efficient real time solutions using acquired knowledge in
various domains to crack problem using suitable mathematical analysis, data structure and
suitable algorithm.
PSO2: To develop environmental and sustainable engineering solution having global and
Societal context using modern IT tools.
PSO3: To exhibit professional and leadership skills with ethical values dealing diversified projects
with excellent communication and documentation qualities
NR23 B.Tech. CSE Syllabus NRCM

COMPUTER NETWORKS LAB

B.Tech. III Year I Sem.


Hours/
Course Code Category Credits Maximum Marks
Week
Professional L T P CIE SEE TOTAL
23CS504 1
Core 0 0 2 40 60 100
Contact Tutorial
Practical Classes: - Total Classes:48
Classes: 48 Classes: Nil
48

Course Objectives
• To understand the working principle of various communication protocols.
• To understand the network simulator environment and visualize a network
topology and observe its performance
• To analyze the traffic flow and the contents of protocol frames

Course Outcomes
• Implement data link layer farming methods
• Analyze error detection and error correction codes.
• Implement and analyze routing and congestion issues in network design.
• Implement Encoding and Decoding techniques used in presentation layer
• To be able to work with different network tools

List of Experiments
1. Implement the data link layer framing methods such as character, character-
stuffing and bit stuffing.
2. Write a program to compute CRC code for the polynomials CRC-12, CRC-16 and CRC
CCIP
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.
4. Implement Dijsktra’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.
6. Implement distance vector routing algorithm for obtaining routing tables at each node.
7. Implement data encryption and data decryption
8. Write a program for congestion control using Leaky bucket algorithm.
9. Write a program for frame sorting techniques used in buffers.
10. Wireshark
i. Packet Capture Using Wire shark
ii. Starting Wire shark
iii. Viewing Captured Traffic
iv. Analysis and Statistics &
Filters. How to run Nmap scan
Operating System Detection using
NR23 B.Tech. CSE Syllabus NRCM
Nmap 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.
vi. Simulate to Plot Congestion for Different Source/Destination
vii. Simulate to Determine the Performance with respect to Transmission of Packets

TEXT BOOK:
1. Computer Networks, Andrew S Tanenbaum, David. j. Wetherall, 5th
Edition. Pearson Education/PHI.

REFERENCE BOOKS:
1. An Engineering Approach to Computer Networks, S. Keshav, 2nd Edition, Pearson
Education.
2. Data Communications and Networking – Behrouz A. Forouzan. 3rd Edition, TMH.
NR23 [COMPUTER NETWORKS LAB]

1. Implement the data link layer framing methods such as character, characterstuffing and bit
stuffing.

1. AIM: To implement the Data Link Layer Framing methods such as Character Count,
Character Stuffing, and Bit Stuffing.

2. ALGORITHM / DESCRIPTION
Character Count Method:
1. Count the number of characters in the frame.
2. Prefix the count at the beginning of the frame.
3. Send the frame with the count byte.
Character Stuffing:
1. Define a special flag character (e.g., #) to mark frame boundaries.
2. Insert an escape character (e.g., \) before each occurrence of the flag or escape character in the
data.
3. Transmit the data with start and end flag.
Bit Stuffing:
1. Monitor the bit stream continuously.
2. After 5 consecutive 1s in the data, insert a 0.
3. At the receiver, after seeing 5 1s followed by 0, remove the stuffed 0.

3. PROGRAM

#include <stdio.h>
#include <string.h>

void characterStuffing() {
char input[50], stuffed[100] = "";
printf("Enter the input string: ");
scanf("%s", input);
strcat(stuffed, "#");
for (int i = 0; i < strlen(input); i++) {
if (input[i] == '#' || input[i] == '\\')
strcat(stuffed, "\\");

M.SHRAVANI,CSE | 1
NR23 [COMPUTER NETWORKS LAB]

strncat(stuffed, &input[i], 1);


}
strcat(stuffed, "#");
printf("Stuffed Data: %s\n", stuffed);
}

void bitStuffing() {
int data[50], stuffed[100], n, i, j = 0, count = 0;
printf("Enter the number of bits: ");
scanf("%d", &n);
printf("Enter the bits: ");
for (i = 0; i < n; i++) scanf("%d", &data[i]);

for (i = 0; i < n; i++) {


if (data[i] == 1) count++;
else count = 0;
stuffed[j++] = data[i];
if (count == 5) {
stuffed[j++] = 0;
count = 0;
}
}
printf("Stuffed Bits: ");
for (i = 0; i < j; i++) printf("%d", stuffed[i]);
printf("\n");
}

int main() {
int choice;
printf("1. Character Stuffing\n2. Bit Stuffing\nEnter your choice: ");
scanf("%d", &choice);

M.SHRAVANI,CSE | 2
NR23 [COMPUTER NETWORKS LAB]

if (choice == 1)
characterStuffing();
else
bitStuffing();
return 0;
}

4. OUTPUT
Output 1: Character Stuffing
Enter the input string: hello#net
Stuffed Data: #hello\#net#

Output 2: Bit Stuffing


Enter the number of bits: 10
Enter the bits: 1 1 1 1 1 1 0 0 1 1
Stuffed Bits: 1111100101

5. VIVA QUESTIONS AND ANSWERS


1. What is the purpose of framing in the data link layer?

Answer: To ensure correct data boundaries and allow the receiver to identify the start and end
of each frame.

2. Differentiate between character and bit stuffing.

Answer: Character stuffing adds escape characters before special bytes, whereas bit stuffing
inserts bits after a sequence of bits.

3. What is a frame delimiter in character stuffing?

Answer: It is a special character (e.g., '#') that marks the start and end of a frame.

4. How is data transparency handled in bit stuffing?

Answer: By inserting 0 after five 1s to avoid confusion with control patterns.

M.SHRAVANI,CSE | 3
NR23 [COMPUTER NETWORKS LAB]

5. What happens if stuffed bits are lost during transmission?

Answer: It may lead to incorrect data interpretation or frame boundary errors.

6. What are escape characters used for?

Answer: To differentiate between data and control characters like frame delimiters.

7. Define synchronous vs asynchronous transmission.

Answer: Synchronous uses a clock signal to sync transmission; asynchronous uses start/stop
bits.

8. How does the receiver know a frame boundary in bit stuffing?

Answer: By detecting the special pattern and removing inserted bits after five 1s.

9. What is the disadvantage of character count framing?

Answer: If the count field is corrupted, the entire frame may be misread.

10. Which method is more efficient and why?

Answer: Bit stuffing is often more reliable for binary streams; character stuffing is easier for
text-based protocols.

M.SHRAVANI,CSE | 4
NR23 [COMPUTER NETWORKS LAB]

2. Write a program to compute CRC code for the polynomials CRC-12, CRC-16 and CRC CCIP

1. AIM: To write a program to compute CRC code for the polynomials CRC-12, CRC-16,
and CRC-CCIP.

2. ALGORITHM / DESCRIPTION
1. Accept input data bits and a divisor polynomial (e.g., CRC-12, CRC-16, or CRC-CCIP).
2. Append zeros (length of divisor - 1) to the input data.
3. Perform binary division (XOR) of the input with the divisor.
4. The remainder is the CRC.
5. Append the CRC to the original data to form the transmitted frame.

3. C PROGRAM

#include <stdio.h>
#include <string.h>

void xorOperation(char *dividend, char *divisor, int len) {


for (int i = 0; i < len; i++) {
dividend[i] = dividend[i] == divisor[i] ? '0' : '1';
}
}

void computeCRC(char data[], char divisor[]) {


int dataLen = strlen(data), divisorLen = strlen(divisor);
char temp[100], crc[50];

strcpy(temp, data);
for (int i = 0; i < divisorLen - 1; i++)
strcat(temp, "0");

char current[100];
strncpy(current, temp, divisorLen);

M.SHRAVANI,CSE | 5
NR23 [COMPUTER NETWORKS LAB]

current[divisorLen] = '\0';

for (int i = divisorLen; i <= strlen(temp); i++) {


if (current[0] == '1')
xorOperation(current, divisor, divisorLen);
memmove(current, current + 1, divisorLen - 1);
current[divisorLen - 1] = temp[i];
}
strcpy(crc, current);
printf("CRC: %s\n", crc);
printf("Transmitted Frame: %s%s\n", data, crc);
}

int main() {
char data[50], crc12[] = "1100000001111", crc16[] =
"11000000000000101", ccip[] =
"100000100110000010001110110110111";
int choice;

printf("Enter data bits: ");


scanf("%s", data);

printf("Choose CRC type:\n1. CRC-12\n2. CRC-16\n3. CRC-


CCIP\nEnter choice: ");
scanf("%d", &choice);

switch (choice) {
case 1: computeCRC(data, crc12); break;
case 2: computeCRC(data, crc16); break;
case 3: computeCRC(data, ccip); break;
default: printf("Invalid choice!\n");

M.SHRAVANI,CSE | 6
NR23 [COMPUTER NETWORKS LAB]

}
return 0;
}

4. OUTPUT
Sample Input:
Enter data bits: 1101011011
Choose CRC type:
1. CRC-12
2. CRC-16
3. CRC-CCIP
Enter choice: 1

Output:
CRC: 100000111111
Transmitted Frame: 1101011011100000111111

5. VIVA QUESTIONS AND ANSWERS


1. What is the purpose of CRC?

Answer: CRC is used for error detection in digital data transmission.

2. How does CRC differ from parity check?

Answer: CRC detects more complex errors than parity, which can only detect odd numbers of
bit errors.

3. What is a generator polynomial?

Answer: It is a predetermined binary divisor used in the CRC calculation.

4. Why do we append zeros in CRC computation?

Answer: To make space for the CRC bits in the calculation.

5. What is the role of XOR in CRC?

M.SHRAVANI,CSE | 7
NR23 [COMPUTER NETWORKS LAB]

Answer: XOR simulates binary division in modulo-2 arithmetic.

6. Can CRC detect all errors?

Answer: It can detect most common errors, but not all possible errors.

7. What happens if the receiver recomputes a different CRC?

Answer: It indicates that an error occurred during transmission.

8. What is the length of CRC-12?

Answer: 12 bits.

9. Is CRC used in real-world protocols?

Answer: Yes, CRC is used in Ethernet, HDLC, USB, and other communication standards.

10. Can we use any polynomial for CRC?

Answer: Only specific, standardized polynomials are used to ensure effective error detection.

M.SHRAVANI,CSE | 8
NR23 [COMPUTER NETWORKS LAB]

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.

1. AIM
To 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.

2. ALGORITHM / DESCRIPTION
1. Set sender window size (N).
2. Send N frames initially.
3. Wait for acknowledgments (ACKs) from the receiver.
4. If ACK received, slide the window and send next frame.
5. If ACK not received within timeout, resend all frames from last ACK.
6. Repeat until all frames are acknowledged.

3. C PROGRAM

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define MAX 10

int main() {
int frames[MAX], i, windowSize, sent = 0, ack;

printf("Enter number of frames to send: ");


int n;
scanf("%d", &n);

for (i = 0; i < n; i++) frames[i] = i;

M.SHRAVANI,CSE | 9
NR23 [COMPUTER NETWORKS LAB]

printf("Enter window size: ");


scanf("%d", &windowSize);

while (sent < n) {


printf("\nSending frames:");
for (i = sent; i < sent + windowSize && i < n; i++) {
printf(" %d", frames[i]);
}

srand(time(NULL));
ack = sent + (rand() % windowSize); // simulate random ACK loss

if (ack >= n) ack = n - 1;

printf("\nAcknowledgment received for frame: %d", ack);

if (ack >= sent)


sent = ack + 1;
else
printf("\nTimeout occurred. Resending from frame %d.", sent);
}

printf("\nAll frames sent successfully.\n");


return 0;
}

4. OUTPUT
Sample Output:
Enter number of frames to send: 5
Enter window size: 3

M.SHRAVANI,CSE | 10
NR23 [COMPUTER NETWORKS LAB]

Sending frames: 0 1 2
Acknowledgment received for frame: 1

Sending frames: 2 3 4
Acknowledgment received for frame: 4

All frames sent successfully.

5. VIVA QUESTIONS AND ANSWERS


1. What is the sliding window protocol?

Answer: It is a flow control method that allows multiple frames to be sent before needing an
acknowledgment.

2. What is Go-Back-N ARQ?

Answer: An error control protocol that resends all frames from the last unacknowledged frame
after a timeout.

3. How is Go-Back-N different from Selective Repeat?

Answer: Go-Back-N resends all frames after a lost one, while Selective Repeat resends only
the lost frames.

4. What is a window size?

Answer: It is the maximum number of frames the sender can send without waiting for an
acknowledgment.

5. Why is flow control needed?

Answer: To prevent overwhelming the receiver with too many frames at once.

6. What happens when an ACK is not received?

Answer: The sender assumes loss and resends all unacknowledged frames.

7. How does the receiver respond to a damaged frame?

M.SHRAVANI,CSE | 11
NR23 [COMPUTER NETWORKS LAB]

Answer: It discards the frame and does not send an ACK, prompting retransmission.

8. What is cumulative acknowledgment?

Answer: ACK for a frame implies that all previous frames have been received correctly.

9. What are the advantages of Go-Back-N?

Answer: Simple implementation and suitable for reliable networks.

10. What is the limitation of Go-Back-N?

Answer: Bandwidth may be wasted due to retransmission of correctly received frames.

M.SHRAVANI,CSE | 12
NR23 [COMPUTER NETWORKS LAB]

4. Implement Dijsktra’s algorithm to compute the shortest path through a network

1. AIM:To implement Dijkstra’s algorithm to compute the shortest path through a network.

2. ALGORITHM / DESCRIPTION

1. Set initial distance to all nodes as infinity except source as 0.


2. Mark all nodes unvisited. Set the source as current node.
3. For current node, update distances to each unvisited neighbor.
4. Select the unvisited node with the smallest distance and set as current.
5. Repeat until all nodes are visited.
6. Final distances represent shortest path from source to all other nodes.

3. C PROGRAM
#include <stdio.h>
#define INF 9999
#define MAX 10

void dijkstra(int graph[MAX][MAX], int n, int start) {


int distance[MAX], visited[MAX] = {0}, i, j, min, nextNode;

for (i = 0; i < n; i++) distance[i] = graph[start][i];


visited[start] = 1;

for (i = 1; i < n; i++) {


min = INF;
for (j = 0; j < n; j++) {
if (!visited[j] && distance[j] < min) {
min = distance[j];
nextNode = j;

M.SHRAVANI,CSE | 13
NR23 [COMPUTER NETWORKS LAB]

}
}
visited[nextNode] = 1;
for (j = 0; j < n; j++) {
if (!visited[j] && distance[nextNode] + graph[nextNode][j] < distance[j]) {
distance[j] = distance[nextNode] + graph[nextNode][j];
}
}
}

printf("Shortest distances from node %d:\n", start);


for (i = 0; i < n; i++) printf("To node %d: %d\n", i, distance[i]);
}

int main() {
int graph[MAX][MAX], n, i, j, start;
printf("Enter number of nodes: ");
scanf("%d", &n);

printf("Enter the adjacency matrix (9999 for no path):\n");


for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
scanf("%d", &graph[i][j]);

printf("Enter starting node (0 to %d): ", n - 1);


scanf("%d", &start);

dijkstra(graph, n, start);
return 0;
}

M.SHRAVANI,CSE | 14
NR23 [COMPUTER NETWORKS LAB]

4. OUTPUT
Enter number of nodes: 4
Enter the adjacency matrix (9999 for no path):
0 3 9999 7
3 0 1 9999
9999 1 0 2
7 9999 2 0
Enter the starting node (0 to 3): 0

Shortest distances from node 0:


To node 0: 0
To node 1: 3
To node 2: 4
To node 3: 6

5. VIVA QUESTIONS AND ANSWERS

1. What is Dijkstra’s algorithm used for?


To find the shortest path from a source node to all other nodes in a graph.
2. Is Dijkstra’s algorithm greedy?
Yes, it uses a greedy method to choose the next nearest node.
3. Can it handle negative edge weights?
No, Dijkstra’s algorithm doesn’t work with negative weights.
4. Where is it used in networking?
It is used in link-state routing protocols like OSPF.
5. What is the time complexity?
O(V²) for simple implementation; can be optimized with priority queue.
6. What data structure improves performance?
Priority queue or min-heap.
7. What is the difference between Dijkstra and Bellman-Ford?
Bellman-Ford works with negative weights, Dijkstra doesn’t.

M.SHRAVANI,CSE | 15
NR23 [COMPUTER NETWORKS LAB]

8. How are unreachable nodes handled?


By setting distance to INF (e.g., 9999).
9. What is the base idea of the algorithm?
Iteratively select the unvisited node with the smallest distance.
10. What is a visited array?
It tracks which nodes have already had their shortest path found.

M.SHRAVANI,CSE | 16
NR23 [COMPUTER NETWORKS LAB]

5. Take an example subnet of hosts and obtain a broadcast tree for the subnet.

1. AIM: To take an example subnet of hosts and obtain a broadcast tree for the subnet.

2. ALGORITHM / DESCRIPTION

1. Represent the subnet as a weighted undirected graph where nodes are hosts and edges are
connections with cost.
2. Use Prim’s algorithm to find the Minimum Spanning Tree (MST).
3. Start with an arbitrary node as the root of the tree.
4. Add the nearest node not in the tree by selecting the minimum weight edge.
5. Repeat until all nodes are included.
6. The resulting MST represents the broadcast tree.

3. C PROGRAM
#include <stdio.h>
#define INF 9999
#define MAX 20

int main() {
int cost[MAX][MAX], visited[MAX] = {0}, i, j, n, no_edges = 0;
int min, a, b, total_cost = 0;

printf("Enter number of nodes (hosts): ");


scanf("%d", &n);

printf("Enter the cost adjacency matrix (9999 if no direct edge):\n");


for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
scanf("%d", &cost[i][j]);

M.SHRAVANI,CSE | 17
NR23 [COMPUTER NETWORKS LAB]

visited[0] = 1;
printf("Edges in the broadcast tree:\n");

while (no_edges < n - 1) {


min = INF;
for (i = 0; i < n; i++) {
if (visited[i]) {
for (j = 0; j < n; j++) {
if (!visited[j] && cost[i][j] < min) {
min = cost[i][j];
a = i;
b = j;
}
}
}
}
printf("%d - %d : %d\n", a, b, cost[a][b]);
total_cost += cost[a][b];
visited[b] = 1;
no_edges++;
}

printf("Total cost of broadcast tree: %d\n", total_cost);


return 0;
}

4. OUTPUT
yaml
CopyEdit
Enter number of nodes (hosts): 4
M.SHRAVANI,CSE | 18
NR23 [COMPUTER NETWORKS LAB]

Enter the cost adjacency matrix:


0 2 9999 6
2038
9999 3 0 1
6810

Edges in the broadcast tree:


0-1:2
1-2:3
2-3:1

Total cost of broadcast tree: 6

5. VIVA QUESTIONS AND ANSWERS

1. What is a broadcast tree?


It is a spanning tree used to send data to all nodes in a network efficiently.
2. Which algorithm is commonly used to build a broadcast tree?
Prim’s or Kruskal’s algorithm can be used to construct the tree.
3. Why do we use MST for broadcasting?
To minimize the total cost while covering all nodes.
4. What does each edge represent in the tree?
A direct communication link between two hosts.
5. What is the time complexity of Prim’s algorithm?
O(V²) for adjacency matrix implementation.
6. How do you avoid loops in the tree?
By keeping track of visited nodes.
7. Can broadcast trees change over time?
Yes, especially in dynamic networks where links go up or down.
8. What is the root of a broadcast tree?
The node where broadcasting begins.

M.SHRAVANI,CSE | 19
NR23 [COMPUTER NETWORKS LAB]

9. Is broadcast the same as multicast?


No, broadcast sends to all nodes; multicast sends to a specific group.
10. Where are broadcast trees used?
In network layer protocols and data distribution applications.

M.SHRAVANI,CSE | 20
NR23 [COMPUTER NETWORKS LAB]

6. Implement distance vector routing algorithm for obtaining routing tables at each node.

1. AIM:To implement the Distance Vector Routing Algorithm for obtaining routing tables at
each node in a subnet.

2. ALGORITHM / DESCRIPTION

1. Initialize the routing table of each node with direct link costs to neighbors.
2. Set the cost to self as 0 and to unreachable nodes as ∞.
3. Exchange routing tables periodically with immediate neighbors.
4. Update each node's table using the Bellman-Ford equation:

D[x][y] = min{ D[x][y], D[x][z] + D[z][y] }

5. Repeat the process until no more updates occur (convergence).


6. Final routing tables show the shortest distance from each node to all others.

3. C PROGRAM
#include <stdio.h>
#define INFINITY 9999
#define MAX 10

int main() {
int cost[MAX][MAX], dist[MAX][MAX], via[MAX][MAX];
int n, i, j, k;

printf("Enter number of nodes: ");


scanf("%d", &n);

printf("Enter the cost matrix (9999 for no direct path):\n");


for (i = 0; i < n; i++) {

M.SHRAVANI,CSE | 21
NR23 [COMPUTER NETWORKS LAB]

for (j = 0; j < n; j++) {


scanf("%d", &cost[i][j]);
dist[i][j] = cost[i][j];
if (i == j)
via[i][j] = i;
else if (cost[i][j] != INFINITY)
via[i][j] = j;
else
via[i][j] = -1;
}
}

for (k = 0; k < n; k++) {


for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
if (dist[i][k] + dist[k][j] < dist[i][j]) {
dist[i][j] = dist[i][k] + dist[k][j];
via[i][j] = via[i][k];
}
}
}
}

for (i = 0; i < n; i++) {


printf("\nRouting table for node %d:\n", i);
printf("Destination\tNext Hop\tCost\n");
for (j = 0; j < n; j++) {
if (dist[i][j] == INFINITY)
printf("%d\t\t-\t\tINF\n", j);
else
printf("%d\t\t%d\t\t%d\n", j, via[i][j], dist[i][j]);

M.SHRAVANI,CSE | 22
NR23 [COMPUTER NETWORKS LAB]

}
}

return 0;
}

4. OUTPUT
Enter number of nodes: 3
Enter the cost matrix:
027
201
710

Routing table for node 0:


Destination Next Hop Cost
0 0 0
1 1 2
2 1 3

Routing table for node 1:


Destination Next Hop Cost
0 0 2
1 1 0
2 2 1

Routing table for node 2:


Destination Next Hop Cost
0 1 3
1 1 1
2 2 0

M.SHRAVANI,CSE | 23
NR23 [COMPUTER NETWORKS LAB]

5. VIVA QUESTIONS AND ANSWERS

1. What is the goal of distance vector routing?


To determine the shortest path from each node to every other node.
2. Which algorithm does distance vector routing use?
It uses the Bellman-Ford algorithm.
3. How does information propagate between nodes?
Nodes exchange their distance vectors with neighbors.
4. What is the count-to-infinity problem?
It occurs when bad news (like a broken link) takes a long time to propagate through the
network.
5. How is infinity defined in the program?
As a large constant value like 9999 to represent unreachable paths.
6. What does the via[i][j] array store?
It stores the next hop (intermediate node) for a path from i to j.
7. What is convergence in distance vector routing?
It is the state where no more updates are made to the routing tables.
8. How does this differ from link state routing?
Distance vector uses neighbor updates; link state floods network topology.
9. What is the complexity of this algorithm?
O(n³) due to triple nested loops in the implementation.
10. Is distance vector routing dynamic?
Yes, it updates routes dynamically as changes occur in the network.

M.SHRAVANI,CSE | 24
NR23 [COMPUTER NETWORKS LAB]

Experiment -7
7. Implement data encryption and data decryption

1. AIM

To implement data encryption and data decryption using a simple algorithm.

2. ALGORITHM / DESCRIPTION

1. Accept a plaintext string and a key from the user.


2. For encryption, convert each character using:
cipher = (char + key) % 256
3. For decryption, convert each character using:
plain = (cipher - key + 256) % 256
4. Display the encrypted and decrypted strings.

3. C PROGRAM
#include <stdio.h>
#include <string.h>

void encrypt(char str[], int key) {


for (int i = 0; str[i] != '\0'; i++) {
str[i] = (str[i] + key) % 256;
}
}

void decrypt(char str[], int key) {


for (int i = 0; str[i] != '\0'; i++) {
str[i] = (str[i] - key + 256) % 256;
}

M.SHRAVANI,CSE | 25
NR23 [COMPUTER NETWORKS LAB]

int main() {
char message[100];
int key;

printf("Enter message to encrypt: ");


fgets(message, sizeof(message), stdin);
message[strcspn(message, "\n")] = '\0';

printf("Enter encryption key (integer): ");


scanf("%d", &key);

encrypt(message, key);
printf("Encrypted message: %s\n", message);

decrypt(message, key);
printf("Decrypted message: %s\n", message);

return 0;
}

4. OUTPUT
pgsql
CopyEdit
Enter message to encrypt: hello
Enter encryption key (integer): 3
Encrypted message: khoor
Decrypted message: hello

M.SHRAVANI,CSE | 26
NR23 [COMPUTER NETWORKS LAB]

5. VIVA QUESTIONS AND ANSWERS

1. What is encryption?
It is the process of converting plaintext into unreadable ciphertext.
2. What is decryption?
It is the process of converting ciphertext back into readable plaintext.
3. What is a cipher?
It is an algorithm used to perform encryption or decryption.
4. What is a key in encryption?
A value used in the algorithm to transform data during encryption or decryption.
5. What type of encryption is used here?
Simple symmetric encryption (Caesar cipher style).
6. What is symmetric encryption?
Encryption where the same key is used for both encryption and decryption.
7. What is ASCII value manipulation in encryption?
It uses arithmetic on ASCII values to alter characters.
8. Can this method protect sensitive data?
No, it's too simple and not secure for real-world use.
9. What is the advantage of symmetric encryption?
It is fast and easy to implement.
10. What is one disadvantage of symmetric encryption?
Key distribution must be secure; otherwise, data is compromised.

M.SHRAVANI,CSE | 27
NR23 [COMPUTER NETWORKS LAB]

Experiment- 8

1. AIM:To write a program for congestion control using the Leaky Bucket algorithm.

2. ALGORITHM / DESCRIPTION

1. Initialize bucket capacity, output rate, and incoming packet rate.


2. For each time unit, perform the following:
o Add incoming packets to the bucket.
o If bucket overflows, discard excess packets.
o Leak packets out at a constant output rate.
3. Repeat for a specified number of cycles or until all packets are processed.
4. Display bucket status and packets sent/discarded.

3. C PROGRAM
#include <stdio.h>

int main() {
int bucket_size, output_rate, n, i;
int input[20], storage = 0, dropped;

printf("Enter bucket size: ");


scanf("%d", &bucket_size);
printf("Enter output rate: ");
scanf("%d", &output_rate);
printf("Enter number of input time slots: ");
scanf("%d", &n);
printf("Enter incoming packet size at each time slot:\n");
for (i = 0; i < n; i++) {
printf("Time %d: ", i + 1);
scanf("%d", &input[i]);

M.SHRAVANI,CSE | 28
NR23 [COMPUTER NETWORKS LAB]

for (i = 0; i < n; i++) {


printf("\nTime %d:\n", i + 1);
printf("Incoming packet size: %d\n", input[i]);

if ((input[i] + storage) > bucket_size) {


dropped = (input[i] + storage) - bucket_size;
storage = bucket_size;
} else {
storage += input[i];
dropped = 0;
}

printf("Bucket status: %d/%d\n", storage, bucket_size);


printf("Packets sent: %d\n", (storage >= output_rate) ? output_rate : storage);
storage -= (storage >= output_rate) ? output_rate : storage;
printf("Packets dropped: %d\n", dropped);
}

return 0;
}

4. OUTPUT
yaml
CopyEdit
Enter bucket size: 10
Enter output rate: 4
Enter number of input time slots: 4
Enter incoming packet size at each time slot:
Time 1: 6
M.SHRAVANI,CSE | 29
NR23 [COMPUTER NETWORKS LAB]

Time 2: 5
Time 3: 2
Time 4: 8

Time 1:
Incoming packet size: 6
Bucket status: 6/10
Packets sent: 4
Packets dropped: 0

Time 2:
Incoming packet size: 5
Bucket status: 7/10
Packets sent: 4
Packets dropped: 0

Time 3:
Incoming packet size: 2
Bucket status: 5/10
Packets sent: 4
Packets dropped: 0

Time 4:
Incoming packet size: 8
Bucket status: 9/10
Packets sent: 4
Packets dropped: 3

M.SHRAVANI,CSE | 30
NR23 [COMPUTER NETWORKS LAB]

5. VIVA QUESTIONS AND ANSWERS

1. What is congestion in a network?


It occurs when the demand for resources exceeds the available capacity, causing packet
loss and delay.
2. What is the Leaky Bucket algorithm?
It is a traffic shaping mechanism that controls data flow at a steady rate, preventing
congestion.
3. How does the Leaky Bucket work?
It simulates a bucket with a fixed capacity that leaks at a constant rate regardless of the
input rate.
4. What happens when the bucket overflows?
Packets are discarded or dropped.
5. What is the purpose of output rate in this algorithm?
To regulate how much data exits the system per time unit.
6. How does Leaky Bucket help congestion control?
By smoothing bursty traffic and enforcing flow rate limits.
7. What is the difference between Token Bucket and Leaky Bucket?
Token Bucket allows bursts; Leaky Bucket enforces a constant output rate.
8. Is the Leaky Bucket algorithm stateful?
Yes, it maintains the current state of the bucket (storage level).
9. Can Leaky Bucket prevent all packet loss?
No, it only manages flow; excessive bursts will still result in drops.
10. Where is Leaky Bucket used in networking?
In traffic shaping and Quality of Service (QoS) mechanisms.

M.SHRAVANI,CSE | 31
NR23 [COMPUTER NETWORKS LAB]

Experiment 9: Frame Sorting Techniques in Buffers


9. Write a program for frame sorting techniques used in buffers.

1. AIM

To write a program for sorting out-of-order frames in a buffer using sequence numbers.

2. ALGORITHM / DESCRIPTION

1. Accept a list of frame sequence numbers as input (may be out of order).


2. Store them in a buffer (array).
3. Sort the buffer using a sorting algorithm (e.g., bubble sort or insertion sort).
4. Display the sorted frames (in-order delivery).

3. C PROGRAM
c
CopyEdit
#include <stdio.h>

void sort(int frames[], int n) {


int i, j, temp;
for (i = 0; i < n - 1; i++) {
for (j = 0; j < n - i - 1; j++) {
if (frames[j] > frames[j + 1]) {
temp = frames[j];
frames[j] = frames[j + 1];
frames[j + 1] = temp;
}
}
}

M.SHRAVANI,CSE | 32
NR23 [COMPUTER NETWORKS LAB]

int main() {
int frames[20], n, i;

printf("Enter number of frames: ");


scanf("%d", &n);

printf("Enter frame sequence numbers (out-of-order):\n");


for (i = 0; i < n; i++) {
scanf("%d", &frames[i]);
}

sort(frames, n);

printf("Frames in sorted order:\n");


for (i = 0; i < n; i++) {
printf("%d ", frames[i]);
}
printf("\n");

return 0;
}

4. OUTPUT
Enter number of frames: 5
Enter frame sequence numbers (out-of-order):
41352
Frames in sorted order:
12345

M.SHRAVANI,CSE | 33
NR23 [COMPUTER NETWORKS LAB]

5. VIVA QUESTIONS AND ANSWERS

1. What is frame sorting?


It is the process of rearranging out-of-order frames into correct sequence.
2. Why does out-of-order delivery happen?
It can occur due to varying network paths or delays.
3. What is the role of sequence numbers?
They identify the correct order of frames for reassembly.
4. Which layer handles frame sorting?
Typically handled at the transport layer or data link layer.
5. What happens if frames are not sorted?
Application may receive corrupted or disordered data.
6. What is jitter?
Variation in packet arrival time causing out-of-order delivery.
7. Can frame sorting handle lost frames?
No, it only reorders; error handling is done separately.
8. What data structure can be used for sorting?
Buffers, arrays, heaps or priority queues.
9. Is sorting required in TCP?
Yes, TCP buffers and reorders segments to ensure in-order delivery.
10. What is buffering?
Temporary storage of data to manage variations in flow or arrival order.

M.SHRAVANI,CSE | 34
NR23 [COMPUTER NETWORKS LAB]

Experiment 10: Network Analysis Using Wireshark and NS2 Simulator


10. Wireshark

i. Packet Capture Using Wire shark

ii. Starting Wire shark

iii. Viewing Captured Traffic

iv. Analysis and Statistics & Filters.

How to run Nmap scan Operating System Detection using

Nmap Do the following using NS2 Simulator

i. NS2 Simulator-Introduction
ii. 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

1. AIM

To analyze network traffic using Wireshark and simulate network behavior using NS2 to study
packet drops, throughput, and congestion control.

2. ALGORITHM / DESCRIPTION

A. Wireshark

1. Packet Capture:
o Launch Wireshark and select a network interface.
o Click “Start Capturing Packets” to begin live capture.

M.SHRAVANI,CSE | 35
NR23 [COMPUTER NETWORKS LAB]

2. Starting Wireshark:
o Open the application from the start menu or terminal (wireshark).
3. Viewing Captured Traffic:
o Use the middle pane to examine individual packets.
o Apply filters like ip, tcp, udp, icmp for specific analysis.
4. Analysis and Statistics:
o Use “Statistics” → “Protocol Hierarchy”, “Conversations”, “IO Graphs” to
interpret results.
5. Running Nmap:
o Run nmap -sS <target IP> to perform a SYN scan.
o Use nmap -O <target IP> for OS detection.

B. NS2 Simulator

1. Introduction:
o NS2 is a discrete event simulator used to simulate routing, congestion, and
protocols.
2. Packet Drop Analysis:
o Write a Tcl script with dropping logic using DropTail or RED.
o Analyze using trace file and tools like awk.
3. TCP/UDP Drop Detection:
o Filter trace file for lines with tcp or udp and event d.
4. Congestion Simulation:
o Create two flows to one destination with limited bandwidth and buffer.
5. Data Rate & Throughput Comparison:
o Analyze received packet count and timestamps.
6. Plot Congestion:
o Use Xgraph to visualize congestion points.
7. Performance Evaluation:
o Calculate metrics like throughput, drop ratio, delay using trace files.

M.SHRAVANI,CSE | 36
NR23 [COMPUTER NETWORKS LAB]

3. SAMPLE TCL PROGRAM (NS2 Simulation for Packet Drop)


tcl
CopyEdit
set ns [new Simulator]

set nf [open out.nam w]


$ns namtrace-all $nf

set tf [open out.tr w]


$ns trace-all $tf

set n0 [$ns node]


set n1 [$ns node]

$ns duplex-link $n0 $n1 1Mb 10ms DropTail

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_ 500
$cbr set interval_ 0.005
$cbr attach-agent $udp

$ns at 0.1 "$cbr start"


$ns at 4.0 "$cbr stop"
$ns at 5.0 "finish"

M.SHRAVANI,CSE | 37
NR23 [COMPUTER NETWORKS LAB]

proc finish {} {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam out.nam &
exit 0
}

$ns run

4. OUTPUT

Wireshark:

 Captured packets listed in real-time.


 Filters applied (e.g., tcp.port == 80).
 Protocol statistics: TCP = 60%, UDP = 30%, ICMP = 10%.

Nmap:
nginx
CopyEdit
nmap -sS 192.168.1.1
nmap -O 192.168.1.1

NS2 Trace Output (filtered):


css
CopyEdit
d -t 2.05 -s 0 -d 1 -p tcp ...

 Xgraph shows drop and congestion points.


 Throughput graph plots received data vs time.

M.SHRAVANI,CSE | 38
NR23 [COMPUTER NETWORKS LAB]

5. VIVA QUESTIONS AND ANSWERS

1. What is Wireshark?
It is a network protocol analyzer used to capture and inspect data packets.
2. What is NS2 used for?
NS2 is a simulator used to model computer networks and analyze their behavior.
3. How do you filter TCP traffic in Wireshark?
Use filter tcp or tcp.port == <port number>.
4. What does nmap -O do?
It performs OS detection on a target host.
5. What is the .tr file in NS2?
It is the trace file containing simulation events for analysis.
6. What does the d event in trace file mean?
It indicates a dropped packet.
7. How do you simulate congestion in NS2?
By creating multiple flows to a bottleneck link.
8. What tools are used to analyze NS2 trace files?
awk, perl, or custom scripts.
9. What is throughput?
The rate of successful data delivery over a network channel.
10. What is a NAM file?
NAM is the Network Animator that visually simulates the NS2 network topology.

M.SHRAVANI,CSE | 39

You might also like