CN-lab File
CN-lab File
CN-lab File
1 Implement Framing Techniques - Bit Stuffing, Byte Stuffing, Character Stuffing 2/2/2024
4 Show Net ID, Host ID, and Network Class of the Address 2/2/2024
THEORY
1. Bit Stuffing: Bit stuffing is a method used to ensure
that a particular bit sequence, typically a delimiter
or control character, does not appear in the
transmitted data unintentionally. It's commonly
employed in protocols like HDLC (High-Level Data
Link Control) and CAN (Controller Area Network).
Sender Side:
B efore transmitting data, examines the bit stream
for predefined patterns (e.g., 0111110) that might be mistaken for control characters. When
detected, an extra bit is inserted strategically into the data stream to disrupt the sequence,
preventing confusion with control characters. Typically, this extra bit is inserted after a set
number of consecutive 1 bits. (e.g., after every 5 consecutive 1 bits).
Receiver Side:
Upon receiving data, the receiver monitors the bit stream for stuffed bits. When encountering
these stuffed bit sequences, it recognizes them as such and removes them to restore the original
data stream. Subsequently, the receiver proceeds with processing the data accordingly.
string stuffedData;
int consecutiveOnes = 0;
string stuffedData;
stuffedData += delimiter;
stuffedData += delimiter;
return stuffedData;
}
int main() {
// Bit stuffing
string input = "001111100";
string bitStuffedData = bitStuffing(input);
cout << "Bit stuffed data: \t" << bitStuffedData << endl;
// Character stuffing
input = "0011EF1E1100";
char delimiter = 'F';
char escape = 'E';
string characterStuffedData = characterStuffing(input, delimiter, escape);
cout << "Character stuffed data: " << characterStuffedData << endl;
return 0;
}
RESULT
Input:
- Data to be framed (Binary sequence).
Output:
- Framed data according to the selected technique (e.g., bit stuffed, byte stuffed, or
character stuffed).
EXPERIMENT 2
AIM
To implement CRC generation and error detection.
THEORY
Cyclic Redundancy Check (CRC) is a method used for detecting errors in data transmission. It
involves appending a check code generated by a special algorithm to the data being sent. At
the receiver's end, the same algorithm is applied to verify the integrity of the received data.
CRC works by detecting changes in bits due to transmission faults, ensuring data accuracy. It
is widely used in digital networks and storage devices to enhance data reliability.
CODE
#include<bits/stdc++.h>
using namespace std;
#define lli long long int
RESULT
Input:
Dataword: Binary Sequence
Generator: Binary sequence or Polynomial equation
Output:
Codeword: Codeword generated by the sender Verification
Result:
- If dataword is correct: Display the codeword released by the sender.
- If error detected: Display "Invalid" along with the original codeword and the
corrupted codeword.
EXPERIMENT 3
AIM
To implement error detection and correction using the Hamming code.
THEORY
Hamming code is a popular error detection and error correction method in data
communication. Hamming code can only detect 2-bit error and correct a single bit error which
means it is unable to correct burst errors if may occur while transmission of data.
Hamming code uses redundant bits (extra bits) which are calculated according to the below
formula: -
2r ≥ m+r+1
Where r is the number of redundant bits required and m is the number of data bits.
R is calculated by putting r = 1, 2, 3 … until the above equation becomes true.
R1 bit is appended at position 20
R2 bit is appended at position 21
R3 bit is appended at position 22 and so on.
These redundant bits are then added to the original data for the calculation of error at
receiver’s end.
At receiver’s end with the help of even parity (generally) the erroneous bit position is
identified and since data is in binary we take complement of the erroneous bit position to
correct received data.
Respective index parity is calculated for r1, r2, r3, r4 and so on.
CODE
#include <iostream>
using namespace std;
int main() {
int data[10];
int dataatrec[10], c, c1, c2, c3, i;
cout << "Enter 4 bits of data one by one\n";
cin >> data[0] >> data[1] >> data[2] >> data[4];
Output:
-Hamming codeword with parity and check bits.
-Detected errors, if any, and corrected codeword.
EXPERIMENT 4
AIM
To parse and display network information from an IP address
THEORY
To parse an IPv4 address into its components - Network ID, Host ID, and Network Class:
1. Network Class: IPv4 addresses are divided into different classes based on the range
of their first octet. There are five classes: A, B, C, D, and E. However, Class D (reserved
for multicast) and Class E (experimental) are not used for general addressing. The
class of an IP address is determined by the value of its first octet:
Class A: 0.0.0.0 to 127.255.255.255
Class B: 128.0.0.0 to 191.255.255.255
Class C: 192.0.0.0 to 223.255.255.255
2. Net ID (Network ID): It represents the network portion of the IP address. The
network ID identifies a specific network, and it's determined by the class of the IP
address. The network ID is obtained by preserving the network portion of the IP
address while setting the host portion to zero.
3. Host ID: It represents the host portion of the IP address. The host ID identifies a
specific device within the network. It's obtained by preserving the host portion of the
IP address while setting the network portion to zero.
CODE
#include <iostream>
#include <string>
using namespace std;
if (ipClass == 'A') {
network = str.substr(0, dotPos);
host = str.substr(dotPos + 1);
}
else if (ipClass == 'B') {
size_t secondDotPos = str.find('.', dotPos + 1);
if(secondDotPos == string::npos) {
cout << "Invalid IP address format" << endl;
return;
}
network = str.substr(0, secondDotPos);
host = str.substr(secondDotPos + 1);
}
else if (ipClass == 'C') {
size_t thirdDotPos = str.find('.', dotPos + 1);
if(thirdDotPos == string::npos) {
cout << "Invalid IP address format" << endl;
return;
}
network = str.substr(0, thirdDotPos);
host = str.substr(thirdDotPos + 1);
}
else {
cout << "In this Class, IP address is not divided into Network and Host ID" << endl;
return;
}
int main() {
string ipAddress;
cout << "Enter IP Address: ";
cin >> ipAddress;
RESULT
Input:
- IPv4 address. (32 bits sequence/ DoQed decimal)
Output:
- Network class (A, B, C), Network ID, and Host ID.
EXPERIMENT 5
AIM
To implement the stop-and-wait protocol for unreliable data transmission.
THEORY
Stop-and-Wait Automatic Repeat reQuest (ARQ)
protocol is a type of error-control protocol used
in data transmission over unreliable
communication channels, typically in computer
networks. It ensures reliable delivery of data by
employing a simple mechanism of sending a
frame and waiting for an acknowledgment (ACK)
from the receiver before sending the next frame.
1. Successful Transmission: Sender sends
frame, receiver acknowledges within
timeout.
2. Frame Lost: Sender sends frame, no
acknowledgment received within timeout,
sender retransmits.
3. ACK Lost: Sender sends frame, receiver receives but ACK is lost, sender retransmits
due to timeout.
4. Late ACK: Sender sends frame, receiver acknowledges late, sender retransmits
assuming frame loss.
CODE
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <unistd.h> // Added for sleep() function
int main() {
int i, j, packet[30];
int fsize = 5;
printf("\n\t Frame size: %d\n", fsize);
printf("\n\t Timeout Time: 3 \n");
printf("\n\t ---- DATA LOG \n");
printf("\n FRAME\t DATA\tWAITING\tACKNOW\tRESEND");
for (i = 0; i < fsize; i++) {
packet[i] = rand() % 1000;
printf("\n %d \t %d", i + 1, packet[i]);
while (j == 0 || rand() % 2 == 0) {
sleep(1);
printf("\t1 ");
sleep(1);
for (j = 2; rand() % 2 == 0 && j < 4; j++) {
printf("%d ", j);
sleep(1);
}
if (j == 4)
printf("\t No \tRESENDING...\n %d \t %d", i + 1, packet[i]);
else
break;
}
if (j == 0) {
sleep(1);
printf("\t0 ");
}
printf("\t YES \t No");
}
printf("\n\n ALL DATA PACKETS SENT ----- \n");
return 0;
}
RESULT
Handle three cases: when the frame and
acknowledgement are delivered successfully, when the frame is lost, and when the
acknowledgement is lost. Show the role of the timeout timer in the protocol.
Input:
- Data frames to be transmitted.
- Timeout period for the timer.
Output:
- Success message for successful
transmission.
-Resend the frame if the frame is lost.
-Timeout message
EXPERIMENT 6
AIM
To implement the Go-Back-N ARQ protocol for efficient data transmission.
THEORY
Go Back N Automatic Repeat Request (ARQ) is a sliding window protocol used in the data link
layer for flow control purposes. It allows for the transmission of multiple frames from the
sender to the receiver before receiving acknowledgments, enabling efficient pipelining of
data. Its components are:
CODE
#include<bits/stdc++.h>
#include<ctime>
#define ll long long int
using namespace std;
int main() {
ll tf, N, tt = 0;
srand(time(NULL));
cout << "Enter the Total number of frames: ";
cin >> tf;
cout << "Enter the Window Size: ";
cin >> N;
ll i = 1;
transmission(i, N, tf, tt);
cout << "Total number of frames which were sent and resent are: " << tt <<
endl;
return 0;
}
RESULT
Input:
-Data frames to be transmitted.
-Window size.
-Timeout period for the timer.
Output:
-Success message for successful transmission.
-Resend the message if the frame is lost.
-Timeout message if acknowledgement is lost.
EXPERIMENT 7
AIM
To implement the Selective Repeat ARQ protocol for efficient data transmission.
THEORY
Selective Repeat ARQ is a Sliding Window Protocol used for reliable, in-order delivery over
noisy channels. It resends only damaged or lost frames, identified by NACKs from the
receiver. Frames are buffered for future use. Sender sets timers for each frame and
retransmits on timer expiry or NACK receipt. ACK and NACK include frame sequence
numbers. Receiver sorts frames by sequence numbers. Sender searches for lost frames
identified by NACKs. Components of Selective Repeat ARQ include:
1. Sender: Initiates data transmission, sets timers for each frame, and responds to
NACKs by retransmitting specific frames.
2. Receiver: Receives frames, buffers correctly received frames, sends ACKs for correct
frames, and sends NACKs for lost or damaged frames.
3. ACK (Acknowledgment): Sent by the receiver to confirm correct receipt of a frame.
4. NACK (Negative Acknowledgment): Sent by the receiver to indicate a lost or damaged
frame, prompting the sender to retransmit it.
5. Timer: Set by the sender for each transmitted frame to detect timeouts and trigger
retransmissions.
6. Sequence Numbers: Assigned to each frame to enable identification of lost frames
and facilitate sorting at the receiver's end.
7. Buffer: Used by the receiver to store received frames for sorting and eventual
processing.
CODE
#include<iostream>
int tmp1, tmp2, tmp3, tmp4, tmp5, i, windowsize, noofPacket, morePacket;
using namespace std;
int main()
{
cout<<"Number of frames: ";
cin>>noofPacket;
cout<<"Window Size: ";
cin>>windowsize;
char c;
int receiver(int);
int simulate(int);
int negack(int);
for(int i = 0;i < 10;i++)
rand();
noofPacket = rand()%10;
morePacket = noofPacket;
while(morePacket >= 0)
{
tmp1 = simulate(windowsize);
windowsize -= tmp1;
tmp4 += tmp1;
if(tmp4 > noofPacket)
tmp4 = noofPacket;
for(i = noofPacket - morePacket; i <= tmp4; i++)
cout<<"\nSending Frame "<<i;
tmp2 = receiver(tmp1);
tmp3 += tmp2;
if(tmp3 > noofPacket)
tmp3 = noofPacket;
tmp2 = negack(tmp1);
tmp5 += tmp2;
if(tmp5 != 0)
{
cout<<"\nNo acknowledgement for the frame "<<tmp5;
cout<<"\nRetransmitting frame "<<tmp5;
}
morePacket -= tmp1;
if(windowsize <= 0)
windowsize = 4;
}
cout<<"\n Selective Repeat Protocol Ends. All packets are successfully transmitted.";
}
int receiver(int tmp1)
{
int i;
for(i = 0;i < 5;i++)
rand();
i = rand() % tmp1;
return i;
}
int negack(int tmp1)
{
int i;
for(i = 0;i < 5;i++)
rand();
i = rand() % tmp1;
return i;
}
int simulate(int windowsize)
{
int tmp1, i;
for(i = 0;i < 5;i++)
tmp1 = rand();
if(tmp1 == 0)
tmp1 = simulate(windowsize);
i = tmp1 % windowsize;
if(i == 0)
return windowsize;
else
return tmp1 % windowsize;
}
RESULT
Input:
-Data frames to be transmitted.
-Window size.
-Timeout period for the timer.
Output:
-Success message for successful
transmission.
-Resend the message if the frame is lost.
-Timeout message if acknowledgement is
lost.
EXPERIMENT 8
AIM
To implement the distance vector routing algorithm for routing table calculation.
THEORY
Distance Vector Routing is a routing
algorithm commonly used in Wide
Area Networks (WANs) to compute the
shortest path between a source and
destination. In this method, routers,
the primary devices in a WAN, are
tasked with routing data. They
construct a routing table containing
information about available routes and
use it to deliver packets either directly or through intermediate devices. Initially, each router
holds information about its neighbours, which is then shared among nodes to optimize
routing decisions.
CODE
#include <bits/stdc++.h>
struct node{
unsigned dist[20];
unsigned from[20];
};
int main(){
int costmat[20][20];
int nodes, i, j, k, count = 0;
printf("\nEnter the number of nodes: ");
scanf("%d", &nodes);
// Error handling: Validate user input for nodes (positive integer)
if (nodes <= 0) {
printf("Error: Invalid number of nodes. Please enter a positive integer.\n");
return 1; // Indicate error
}
printf("\nEnter the cost matrix:\n");
for (i = 0; i < nodes; i++){
for (j = 0; j < nodes; j++){
scanf("%d", &costmat[i][j]);
}
}
struct node rt[10]; // Array of routing table entries
THEORY
Link State Routing is a routing algorithm employed in computer networks where each router
shares its knowledge of its immediate neighborhood with every other router in the network.
Instead of sending its entire routing table, a router only transmits information about its
neighbors. This information is distributed to all routers in the network, not just to its
immediate neighbors, through a process called flooding. Additionally, when there is a change
in the network, such as a new router being added or a link going down, each router sends out
updated information about its neighbors to ensure all routers have the most current view of
the network topology.
CODE
#include <iostream>
#include <vector>
#include <limits>
using namespace std;
const int INF = numeric_limits<int>::max();
// Function to find the vertex with minimum distance
int minDistance(const vector<int> &distance, const vector<bool> &visited, int nodes){
int min = INF, min_index;
for (int v = 0; v < nodes; v++) {
if (!visited[v] && distance[v] <= min){
min = distance[v];
min_index = v;
}
}
return min_index;
}
// Function to print the shortest path and distance from a source vertex
void printPath(const vector<int> &parent, int v){
if (parent[v] == -1) {
cout << v << " ";
return;
}
printPath(parent, parent[v]);
cout << v << " ";
}
// Dijkstra's shortest path algorithm
void dijkstra(const vector<vector<int>> &graph, int src, int nodes){
vector<int> distance(nodes, INF);
vector<bool> visited(nodes, false);
vector<int> parent(nodes, -1);
distance[src] = 0;
int main(){
int nodes;
cout << "Enter the number of nodes: ";
cin >> nodes;
vector<vector<int>> graph(nodes, vector<int>(nodes, 0));
cout << "Enter the cost matrix:\n";
for (int i = 0; i < nodes; i++){
for (int j = 0; j < nodes; j++){
cin >> graph[i][j];
if (graph[i][j] == 0)
graph[i][j] = INF; // Set non-existent connections to infinity
}
}
dijkstra(graph, 0, nodes); // Assuming source node as 0
return 0;
}
RESULT
Input: -
Network topology (nodes, links, and link costs).
Output: -
Shortest path tree rooted at the source node.
EXPERIMENT 10
AIM
To implement the Diffie-Hellman key exchange algorithm for secure key exchange
over an insecure channel.
THEORY
The Diffie-Hellman algorithm allows two
parties, Alice and Bob, to securely establish a
shared secret over an insecure network
without directly exchanging it. They agree on
public parameters (a prime number and a
primitive root), then each selects a private
value. Using these private values and the
public parameters, they compute their public
keys. After exchanging public keys, they can
compute the same shared secret
independently. This shared secret can be used for secure communication. Elliptic curve
cryptography (ECC) can further enhance security and performance compared to
traditional methods.
CODE
#include <iostream>
#include <cmath>
using namespace std;
long long int power(long long int a, long long int b, long long int P)
{
if (b == 1)
return a;
else
return (((long long int)pow(a, b)) % P);
}
int main()
{
long long int P, G, x, a, y, b, ka, kb;
x = power(G, a, P);
y = power(G, b, P);
ka = power(y, a, P);
kb = power(x, b, P);
cout << "Secret key for Alice is : " << ka << endl;
cout << "Secret key for Bob is : " << kb << endl;
return 0;
}
RESULT
Input:
-Prime number (p) and primitive root (g) shared by both parties. --
-Private keys (a and b) for each party.
Output:
-Shared secret key generated by both parties.
Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.
Alternative Proxies: