CN-lab File

Download as pdf or txt
Download as pdf or txt
You are on page 1of 27

DELHI TECHNOLOGICAL UNIVERSITY

(Formerly Delhi College of Engineering)


Shahbad Daulatpur, Bawana Road, Delhi- 110042

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

Computer Networks Laboratory


Subject Code: CO-306

SUBMITTED TO: SUBMITTED BY:


Prof. Anukriti Kaushal Manthan Singh
(2K21/CO/274)
INDEX
Remarks
S No. Experiment Date

1 Implement Framing Techniques - Bit Stuffing, Byte Stuffing, Character Stuffing 2/2/2024

2 Implement Cyclic Redundancy Check (CRC) 2/2/2024

3 Implement Error Detection and Correction using Hamming Code 2/2/2024

4 Show Net ID, Host ID, and Network Class of the Address 2/2/2024

5 Implement Stop & Wait ARQ Protocol 20/2/2024

6 Implement Go Back N ARQ Protocol 20/2/2024

7 Implement Selective Repeat ARQ Protocol 20/2/2024

8 Implement Distance Vector Routing Algorithm 11/4/2024

9 Implement Link State Routing Algorithm 11/4/2024

10 Implement the Diffie-Hellman Key Exchange algorithm 11/4/2024


EXPERIMENT 1
AIM
To implement various framing techniques used in data communication to delineate
frames.

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.

2. Byte Stuffing (Character Stuffing): Byte stuffing is a


similar concept to bit stuffing but operates at the byte
level rather than the bit level. It's commonly used in
protocols like PPP (Point-to-Point Protocol) and
XMODEM.
Sender Side:
Similar to bit stuffing, the sender examines the
byte stream for sequences that resemble control characters or delimiters. Upon
detection, the sender inserts an additional byte into the stream acting as an escape
character, signalling that the subsequent byte is data rather than a control character.
Receiver Side:
Upon receiving the data, the receiver scans for escape characters. When an escape
character is found, the receiver understands that the following byte is data, not a
control character. Consequently, the receiver processes the data accordingly,
disregarding the escape characters.
CODE
#include <bits/stdc++.h>
using namespace std;

string bitStuffing(const string& data) {


cout<<"Input string data: \t"<<data<<endl;

const int threshold = 5;


string flag="0";
for(int i=0; i<threshold+1; i++)
flag+="1";
flag+="0";

string stuffedData;
int consecutiveOnes = 0;

for (char bit : data) {


stuffedData += bit;
if (bit == '1') {
consecutiveOnes++;
if (consecutiveOnes == threshold) {
stuffedData += '0';
consecutiveOnes = 0;
}
} else {
consecutiveOnes = 0;
}
}
stuffedData=flag+stuffedData+flag;
return stuffedData;
}

// Function to perform character stuffing


string characterStuffing(const string& data, char delimiter, char escape) {
cout<<"Input string data: \t"<<data<<endl;

string stuffedData;
stuffedData += delimiter;

for (char character : data) {


if (character == delimiter || character == escape) {
stuffedData += escape;
}
stuffedData += character;
}

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

string toBin(lli num) {


string bin = "";
while (num) {
bin = ((num & 1) ? "1" : "0") + bin;
num >>= 1;
}
return bin;
}

lli toDec(string bin) {


lli num = 0;
for (int i = 0; i < bin.length(); i++)
if (bin[i] == '1')
num += 1LL << (bin.length() - i - 1);
return num;
}

void CRCCheck(string codeword, string generator) {


int n = generator.length();
lli gen = toDec(generator), dword = toDec(codeword), rem;
lli dividend = dword << (n - 1);
int shft = ceil(log2(dividend + 1)) - n;
while ((dividend >= gen) || (shft >= 0)) {
rem = (dividend >> shft) ^ gen;
dividend = (dividend & ((1LL << shft) - 1)) | (rem << shft);
shft = ceil(log2(dividend + 1)) - n;
}
cout <<"Remainder: " << dividend <<endl;
cout << "Remainder " << dividend << ((dividend == 0) ? " = 0 , hence no error is detected."
: " != 0 , hence an error is detected during transmission.") << endl << endl;
}

void CRCSender(string dataword, string generator) {


int n = generator.length();
lli gen = toDec(generator), dword = toDec(dataword), rem;
lli dividend = dword << (n - 1);
int shft = ceil(log2(dividend + 1)) - n;
while ((dividend >= gen) || (shft >= 0)) {
rem = (dividend >> shft) ^ gen;
dividend = (dividend & ((1LL << shft) - 1)) | (rem << shft);
shft = ceil(log2(dividend + 1)) - n;
}
lli codeword = (dword << (n - 1)) | dividend;
cout << "Transmitted Codeword : " << toBin(codeword) << endl << endl;
}

void CRC(string dataword, string generator) {


cout << "Sender Side:" << endl;
CRCSender(dataword, generator);
cout << "Receiver Side:" << endl;
string codeword;
CRCCheck(codeword, generator);
// Modify one bit in the codeword
int bitToModify = rand() % codeword.length();
codeword[bitToModify] ^= '0' ^ '1'; // Flip the bit
cout << "Modified Codeword: " << codeword << endl;
CRCCheck(codeword, generator);
}
int main() {
string dataword, generator;
cout << "Enter the dataword: ";
cin >> dataword;
cout << "Enter the generator: ";
cin >> generator;
CRC(dataword, generator);
return 0;
}

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];

// Calculation of even parity


data[6] = data[0] ^ data[2] ^ data[4];
data[5] = data[0] ^ data[1] ^ data[4];
data[3] = data[0] ^ data[1] ^ data[2];

cout << "\nEncoded data is\n";


for (i = 0; i < 7; i++)
cout << data[i];
cout << "\n\nEnter received data bits one by one\n";
for (i = 0; i < 7; i++)
cin >> dataatrec[i];

c1 = dataatrec[6] ^ dataatrec[4] ^ dataatrec[2] ^ dataatrec[0];


c2 = dataatrec[5] ^ dataatrec[4] ^ dataatrec[1] ^ dataatrec[0];
c3 = dataatrec[3] ^ dataatrec[2] ^ dataatrec[1] ^ dataatrec[0];
c = c3 * 4 + c2 * 2 + c1;
if (c == 0) {
cout << "\nNo error while transmission of data\n";
} else {
cout << "\nError on position " << c;
cout << "\nData sent : ";
for (i = 0; i < 7; i++)
cout << data[i];
cout << "\nData received : ";
for (i = 0; i < 7; i++)
cout << dataatrec[i];
cout << "\nCorrect message is\n";
// if erroneous bit is 0 we complement it else vice versa
if (dataatrec[7 - c] == 0)
dataatrec[7 - c] = 1;
else
dataatrec[7 - c] = 0;
for (i = 0; i < 7; i++) {
cout << dataatrec[i];
}
}
return 0;
}
RESULT
Input:
-Dataword (Binary sequence)

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;

char findClass(const string& str) {


size_t dotPos = str.find('.');
if(dotPos == string::npos) {
cout << "Invalid IP address format" << endl;
return '\0'; // Return null character to indicate error
}

string firstOctet = str.substr(0, dotPos);


int ip = stoi(firstOctet);
if (ip >= 1 && ip <= 126)
return 'A';
else if (ip >= 128 && ip <= 191)
return 'B';
else if (ip >= 192 && ip <= 223)
return 'C';
else if (ip >= 224 && ip <= 239)
return 'D';
else
return 'E';
}

void separate(const string& str, char ipClass) {


string network, host;

size_t dotPos = str.find('.');


if(dotPos == string::npos) {
cout << "Invalid IP address format" << endl;
return;
}

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;
}

cout << "Network ID: " << network << endl;


cout << "Host ID: " << host << endl;
}

int main() {
string ipAddress;
cout << "Enter IP Address: ";
cin >> ipAddress;

char ipClass = findClass(ipAddress);


if(ipClass != '\0') {
cout << "IP address belongs to: Class " << ipClass << endl;
separate(ipAddress, ipClass);
}
return 0;
}

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:

 Sender Window: Maintains a fixed-sized window (N) for consecutive frame


transmission.
 Receiver Window: Accepts one frame at a time.
 Operation: Frames sent without waiting for acknowledgments; sender slides window
upon acknowledgment reception.
 Retransmission: If acknowledgment not received or frames arrive out of order,
sender retransmits from corrupted frame.
 Pipelining: Allows transmission before acknowledgment reception, enhancing
efficiency.

CODE
#include<bits/stdc++.h>
#include<ctime>
#define ll long long int
using namespace std;

void transmission(ll & i, ll & N, ll & tf, ll & tt) {


while (i <= tf) {
int z = 0;
for (int k = i; k < i + N && k <= tf; k++) {
cout << "Sending Frame " << k << "..." << endl;
tt++;
}
for (int k = i; k < i + N && k <= tf; k++) {
int f = rand() % 2;
if (!f) {
cout << "Acknowledgment for Frame " << k << "..." << endl;
z++;
} else {
cout << "Timeout!! Frame Number : " << k << " Not Received" << endl;
cout << "Retransmitting Window..." << endl;
break;
}
}
cout << "\n";
i = i + z;
}
}

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

// Initialize routing table (assuming all distances are initially infinite)


for (i = 0; i < nodes; i++){
for (j = 0; j < nodes; j++) {
rt[i].dist[j] = (i == j) ? 0 : INT_MAX; // 0 for same node, INT_MAX for others
rt[i].from[j] = i; // Initially, source is itself
}
}
do{
count = 0;
for (i = 0; i < nodes; i++){
for (j = 0; j < nodes; j++){
for (k = 0; k < nodes; k++){
if (rt[i].dist[j] > costmat[i][k] + rt[k].dist[j]) {
rt[i].dist[j] = costmat[i][k] + rt[k].dist[j];
rt[i].from[j] = k;
count++;
}
}
}
}
} while (count != 0); // Bellman-Ford algorithm for
finding shortest paths
// Print routing table (assuming you still want to print it)
for (i = 0; i < nodes; i++) {
printf("\n\nFor router %d\n", i + 1);
for (j = 0; j < nodes; j++)
printf("\tnode %d via %d Distance %d\n", j + 1, rt[i].from[j] + 1, rt[i].dist[j]);
}
return 0;
}
RESULT
Input: -
Network topology (nodes, links, and link costs).
Output: -
Routing table for each node
EXPERIMENT 9
AIM
To implement the link state routing algorithm for computing shortest paths.

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;

// Find shortest path for all vertices


for (int count = 0; count < nodes - 1; count++) {
int u = minDistance(distance, visited, nodes);
visited[u] = true;

for (int v = 0; v < nodes; v++)


{
if (!visited[v] && graph[u][v] && graph[u][v] + distance[u] < distance[v]) {
parent[v] = u;
distance[v] = distance[u] + graph[u][v];
}
}
}

// Print paths and distances for each destination


for (int i = 1; i < nodes; i++){
cout << "Path: " << i;
if (parent[i] != -1)
printPath(parent, i);
else
cout << " not reachable";
cout << " \nCost: " << distance[i] << endl;
}
}

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;

cout << "Enter the value of prime number (P): ";


cin >> P;
cout << "Enter the value of primitive root (G): ";
cin >> G;
cout << "Enter the private key for Alice (a): ";
cin >> a;
cout << "Enter the private key for Bob (b): ";
cin >> b;

cout << "P: " << P << endl;


cout << "G: " << G << endl;
cout << "a: " << a << endl;
cout << "b: " << b << endl;

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

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:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy