0% found this document useful (0 votes)
28 views68 pages

Ns Lab Manual

The document outlines the implementation of various Data Link Layer framing methods and error detection techniques using C programming. It covers Bit Stuffing, Character Stuffing, LRC, CRC, Hamming Code, as well as Stop and Wait and Sliding Window protocols, providing algorithms, code examples, and execution results for each method. Each section concludes with a verification of the program's execution and results.

Uploaded by

kavitha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views68 pages

Ns Lab Manual

The document outlines the implementation of various Data Link Layer framing methods and error detection techniques using C programming. It covers Bit Stuffing, Character Stuffing, LRC, CRC, Hamming Code, as well as Stop and Wait and Sliding Window protocols, providing algorithms, code examples, and execution results for each method. Each section concludes with a verification of the program's execution and results.

Uploaded by

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

Implement the Data Link Layer framing methods,

i) Bit stuffing, (ii) Character stuffing


Implement the Data Link Layer framing methods,
i) Bit stuffing, (ii) Character stuffing
1.Implement the data link layer framing methods
(i)Bit Stuffing (i)Character stuffing

(i)Bit Stuffing
Aim: To write a program to verify bit stuffing using C Program
Algorithm:
(i) Write the Program using C Language
(ii) Enter the Program
(iii) Run & Execute the Program
(iv) Correct the errors
(v) Feed the Input and get the output
(vi)Stop the program
Program :
#include<stdio.h>
#include<string.h>
int main()
{
int a[20],b[30],i,j,k,count,n;
printf("Enter frame size (Example: 8):");
scanf("%d",&n);
printf("Enter the frame in the form of 0 and 1 :");
for(i=0; i<n; i++)
scanf("%d",&a[i]);
i=0;
count=1;
j=0;
while(i<n)
{
if(a[i]==1)
{
b[j]=a[i];
for(k=i+1; a[k]==1 && k<n && count<5; k++)
{
j++;
b[j]=a[k];
count++;
if(count==5)
{
j++;
b[j]=0;
}
i=k;
}
}
else
{
b[j]=a[i];
}
i++;
j++;
}
printf("After Bit Stuffing :");
for(i=0; i<j; i++)
printf("%d",b[i]);
return 0;
}
_______________________________________________
output
Enter frame size (Example: 8):12
Enter the frame in the form of 0 and 1 :0 1 0 1 1 1 1 1 1 0 0 1
After Bit Stuffing :0101111101001
Result: Thus the given program is executed and the result is verified

(ii)Character stuffing
Aim: To write a program to verify Character stuffing using c program
Algorithm:
(i) Write the Program using C Language
(ii) Enter the Program
(iii) Run & Execute the Program
(iv) Correct the errors
(v) Feed the Input and get the output
(vi)Stop the program
Program :
#include<string.h>
main()
{
char a[30], fs[50] = " ", t[3], sd, ed, x[3], s[3], d[3], y[3];
int i, j, p = 0, q = 0;
clrscr();
printf("Enter characters to be stuffed:");
scanf("%s", a);
printf("\nEnter a character that represents starting delimiter:");
scanf(" %c", &sd);
printf("\nEnter a character that represents ending delimiter:");
scanf(" %c", &ed);
x[0] = s[0] = s[1] = sd;
x[1] = s[2] = '\0';
y[0] = d[0] = d[1] = ed;
d[2] = y[1] = '\0';
strcat(fs, x);
for(i = 0; i < strlen(a); i++)
{
t[0] = a[i];
t[1] = '\0';
if(t[0] == sd)
strcat(fs, s);
else if(t[0] == ed)
strcat(fs, d);
else
strcat(fs, t);
}
strcat(fs, y);
printf("\n After stuffing:%s", fs);
getch();
}
___________________________________________________________________
output
Enter characters to be stuffed: goodday
Enter a character that represents starting delimiter: d
Enter a character that represents ending delimiter: g
After stuffing: dggooddddayg.
Thus the given program is executed and the result is verified
Result: Thus the given program is executed and the result is verified
2)Implementation of Error Detection & Correction Technique
(i)LRC (ii)CRC (iii)Hamming code
(i)LRC
Aim : To write a program to verify LRC using C Program
Algorithm:
(i) Write the Program using C Language
(ii) Enter the Program
(iii) Run & Execute the Program
(iv) Correct the errors
(v) Feed the Input and get the output
(vi)Stop the program
Program :
#include<stdio.h>
#include<conio.h>
void main()
{
int l1,bit[100],count=0,i,choice;
clrscr();
printf("Enter the length of data stream: ");
scanf("%d",&l1);
printf("\nEnter the data stream ");
for(i=0;i<l1;i++)
{
scanf("%d",&bit[i]);
if(bit[i]==1)
count=count+1;
}
printf("Number of 1's are %d",count);
printf("\nEnter the choice to implement parity bit");
printf("\n1-Sender side\n2-Receiver side\n");
scanf("%d",&choice);
switch(choice)
{
case 1:
if(count%2==0)
bit[l1]=0;
else
bit[l1]=1;

printf("\nThe data stream after adding parity bit is\n");


for(i=0;i<=l1;i++)
printf("%d",bit[i]);
break;
case 2:
if(count%2==0)
printf("There is no error in the received data stream");
else
printf("There is error in the received data stream");
break;

default:
printf("Invalid choice");
break;
}
getch();
}
_______________________________________________________________

output
Enter the length of data stream: 10
Enter the data stream 1 1 0 1 0 1 1 1 0 1
Number of 1's are 7
Enter the choice to implement parity bit
1-Sender side
2-Receiver side
1
The data stream after adding parity bit is
11010111011
Enter the length of data stream: 10
Enter the data stream 1 1 1 1 1 0 0 0 1 0
Number of 1's are 6
Enter the choice to implement parity bit
1-Sender side
2-Receiver side
2
There is no error in the received data stream
Result: Thus the given program is executed and the result is verified

(ii)CRC
Aim: To write a program to verify CRC using C Program
Algorithm:
(i) Write the Program using C Language
(ii) Enter the Program
(iii) Run & Execute the Program
(iv) Correct the errors
(v) Feed the Input and get the output
(vi)Stop the program
Program :
#include <stdio.h>
#include <string.h>
#define CRC_POLY 0xEDB88320L // CRC polynomial
unsigned long crc_table[256];
// Calculate CRC table
void crc_init(void)
{
int i, j;
unsigned long crc;
for (i = 0; i < 256; i++) {
crc = i;
for (j = 0; j < 8; j++) {
if (crc & 1) {
crc = (crc >> 1) ^ CRC_POLY;
} else {
crc >>= 1;
}
}
crc_table[i] = crc;
}
}
// Calculate CRC value for given data
unsigned long crc_calculate(char *data, int length)
{
unsigned long crc = 0xFFFFFFFFL;
int i;
for (i = 0; i < length; i++)
{
crc = crc_table[(crc ^ data[i]) & 0xFF] ^ (crc >> 8);
}
return crc ^ 0xFFFFFFFFL;
}
int main()
{
char data[] = "Hello, world!";
int length = strlen(data);
unsigned long crc;
// Initialize CRC table
crc_init();
// Calculate CRC value
crc = crc_calculate(data, length);
printf("Data: %s\n", data);
printf("Data length: %d\n", length);
printf("CRC value: 0x%08lx\n", crc);
return 0;
}
______________________________________________________________
output
Data: Hello, world!
Data length: 13
CRC value: 0x46af4db4
Result: Thus the given program is executed and the result is verified

(iii)Hamming Code
Aim : To verify the Hamming code
Algorithm:
(i) Write the Program using C Language
(ii) Enter the Program
(iii) Run & Execute the Program
(iv) Correct the errors
(v) Feed the Input and get the output
(vi)Stop the program
Program :
#include <stdio.h>
#include <stdlib.h>

// Calculate parity bit for a given data bit position


int calculate_parity(int *data, int size, int pos) {
int parity = 0;
for (int i = pos - 1; i < size; i += pos * 2) {
for (int j = i; j < i + pos && j < size; j++) {
parity ^= data[j];
}
}
return parity;
}
// Encode data using Hamming code
int *hamming_encode(int *data, int size) {
int parity_bits = 0;
while ((1 << parity_bits) < size + parity_bits + 1) {
parity_bits++;
}
int *encoded = malloc((size + parity_bits) * sizeof(int));
int j = 0;
for (int i = 0; i < size + parity_bits; i++) {
if ((i + 1) == (1 << j)) {
encoded[i] = 0;
j++;
} else {
encoded[i] = data[i - j];
}
}
for (int i = 0; i < parity_bits; i++) {
int pos = 1 << i;
int parity = calculate_parity(encoded, size + parity_bits, pos);
encoded[pos - 1] = parity;
}
return encoded;
}
// Decode data using Hamming code
int *hamming_decode(int *data, int size) {
int parity_bits = 0;
while ((1 << parity_bits) < size + 1) {
parity_bits++;
}
int *decoded = malloc(size * sizeof(int));
int error_pos = 0;
for (int i = 0; i < parity_bits; i++) {
int pos = 1 << i;
int parity = calculate_parity(data, size, pos);
if (parity != data[pos - 1]) {
error_pos += pos;
}
}
if (error_pos > 0) {
data[error_pos - 1] ^= 1;
}
int j = 0;
for (int i = 0; i < size; i++) {
if ((i + 1) == (1 << j)) {
j++;
} else {
decoded[i - j] = data[i];
}
}
return decoded;
}
int main() {
int size;
printf("Enter size of data: ");
scanf("%d", &size);
int data[size];
printf("Enter data bits (separated by space): ");
for (int i = 0; i < size; i++) {
scanf("%d", &data[i]);
}
// Encode data using Hamming code
int *encoded = hamming_encode(data, size);

// Print encoded data


printf("Encoded data: ");
for (int i = 0; i < size + 2; i++) {
printf("%d ", encoded[i]);
}
printf("\n");

// Introduce error in encoded data


int error_pos;
printf("Enter position of error (1-%d, 0 for no error): ", size + 2);
scanf("%d", &error_pos);
if (error_pos > 0 && error_pos <= size + 2) {
encoded[error_pos - 1] ^= 1;
}
Result: Thus the given program is executed and the result is verified
(3)Implementation of Stop & Wait and Sliding Window protocols
(i)Stop and Wait Protocol

Aim : To write a program to implementation of stop & wait and sliding window protocols
Algorithm:
(i) Write the Program using C Language
(ii) Enter the Program
(iii) Run & Execute the Program
(iv) Correct the errors
(v) Feed the Input and get the output
(vi)Stop the program
Program :
#include <stdio.h>
#include <stdlib.h>
#define TIMEOUT 10 // timeout in seconds
// Simulate sending data over unreliable channel
int send_data(int data) {
int success = rand() % 2; // randomly decide if transmission is successful
if (success) {
printf("Data %d transmitted successfully.\n", data);
return 1;
} else {
printf("Data %d transmission failed.\n", data);
return 0;
}
}
// Simulate receiving data over unreliable channel
int receive_data()
{
int success = rand() % 2; // randomly decide if transmission is successful
if (success)
{
printf("Data received successfully.\n");
return 1;
}
else
{
printf("Data reception failed.\n");
return 0;
}
}
// Simulate timeout
void simulate_timeout() {
printf("Timeout occurred.\n");
}
int main() {
int data = 0;
int seq_num = 0;
int ack_num = 0;
int timeout = 0;
while (1) {
if (timeout) {
simulate_timeout();
timeout = 0;
} else {
printf("Sending data %d with sequence number %d.\n", data, seq_num);
int success = send_data(data);
if (success) {
ack_num = seq_num;
seq_num = (seq_num + 1) % 2;
data++;
timeout = 1;
}
}
printf("Expecting ACK %d.\n", ack_num);
int success = receive_data();
if (success && ack_num == seq_num) {
timeout = 0;
}
}
return 0;
}
___________________________________________________________________
output
Sending data 0 with sequence number 0.
Data 0 transmitted successfully.
Expecting ACK 0.
Data received successfully.
Sending data 1 with sequence number 1.
Data 1 transmission failed.
Expecting ACK 0.
Data reception failed.
Timeout occurred.
Sending data 1 with sequence number 1.
Data 1 transmission failed.
Expecting ACK 0.
Data reception failed.
Timeout occurred.
Sending data 1 with sequence number 1.
Data 1 transmission failed.
Expecting ACK 0.
Data received successfully.
Result: Thus the given program is executed and the result is verified

(ii)Sliding Window Protocols


Aim : To write a program to execute sliding window protocols
Algorithm:
(i) Write the Program using C Language
(ii) Enter the Program
(iii) Run & Execute the Program
(iv) Correct the errors
(v) Feed the Input and get the output
(vi)Stop the program
Program :
#include <stdio.h>
#include <stdlib.h>
#define WINDOW_SIZE 4 // window size
#define TIMEOUT 10 // timeout in seconds

// Simulate sending data over unreliable channel


int send_data(int data)
{
int success = rand() % 2; // randomly decide if transmission is successful
if (success)
{
printf("Data %d transmitted successfully.\n", data);
return 1;
}
else
{
printf("Data %d transmission failed.\n", data);
return 0;
}
}
// Simulate receiving data over unreliable channel
int receive_data()
{
int success = rand() % 2; // randomly decide if transmission is successful
if (success)
{
printf("Data received successfully.\n");
return 1;
} else {
printf("Data reception failed.\n");
return 0;
}
}
// Simulate timeout
void simulate_timeout() {
printf("Timeout occurred.\n");
}
int main() {
int data = 0;
int seq_num = 0;
int ack_num = 0;
int timeout = 0;
while (1) {
if (timeout) {
simulate_timeout();
seq_num = ack_num;
timeout = 0;
}
int i;
for (i = 0; i < WINDOW_SIZE && seq_num + i < ack_num + WINDOW_SIZE; i++) {
printf("Sending data %d with sequence number %d.\n", data, seq_num + i);
int success = send_data(data);
if (success) {
data++;
}
}
if (i == 0) {
continue;
}
printf("Expecting ACK %d.\n", ack_num);
int success = receive_data();
if (success) {
ack_num += i;
timeout = 1;
}
}
return 0;
}
___________________________________________________________________
output
Sending data 0 with sequence number 0.
Data 0 transmitted successfully.
Sending data 1 with sequence number 1.
Data 1 transmission failed.
Sending data 1 with sequence number 2.
Data 1 transmission failed.
Sending data 1 with sequence number 3.
Data 1 transmission failed.
Sending data 1 with sequence number 4.
Data 1 transmission failed.
Expecting ACK 0.
Data reception failed.
Timeout occurred.
Sending data 1 with sequence number 0.
Data 1 transmitted successfully.
Sending data 2 with sequence number 1.
Data 2 transmission failed.
Sending data 2 with sequence number 2.
Data 2 transmission failed.
Sending data 2 with sequence number 3.
Data 2 transmission failed.
Sending data 2 with sequence number 4.
Data 2 transmission failed.
Expecting ACK 1.
Data reception failed.
Timeout occurred.
Sending data 2 with sequence number 1.
Data 2 transmission failed.
Sending data 2 with sequence number 2.
Data 2 transmission failed.
Sending data 2 with sequence number 3.
Data 2 transmission failed.
Sending data 2 with sequence number 4.
Data 2 transmission failed.
Expecting ACK 1.
Data reception failed.
Timeout occurred.
Sending data 2 with sequence number 1.
Data 2 transmission failed.
Sending data 2 with sequence number 2.
Data 2 transmission failed.
Sending data 2 with sequence number 3.
Data 2 transmission failed.
Sending data 2 with sequence number 4.
Data 2 transmission failed.
Expecting ACK 1.
Data reception failed
Result: Thus the given program is executed and the result is verified
4)Implementation of Go-back-N & Selective Repeat Protocol

(i) Go-back - N Protocol


Aim : To write a program to implement of Go Back N protocol using C Program
Algorithm:
(i) Write the Program using C Language
(ii) Enter the Program
(iii) Run & Execute the Program
(iv) Correct the errors
(v) Feed the Input and get the output
(vi)Stop the program
Program :
#include<stdio.h>
int main()
{
int windowsize,sent=0,ack,i;
printf("enter window size\n");
scanf("%d",&windowsize);
while(1)
{
for( i = 0; i < windowsize; i++)
{
printf("Frame %d has been transmitted.\n",sent);
sent++;
if(sent == windowsize)
break;
}
printf("\nPlease enter the last Acknowledgement received.\n");
scanf("%d",&ack);

if(ack == windowsize)
break;
else
sent = ack;
}
return 0;
}
output:-
enter window size
8
Frame 0 has been transmitted.
Frame 1 has been transmitted.
Frame 2 has been transmitted.
Frame 3 has been transmitted.
Frame 4 has been transmitted.
Frame 5 has been transmitted.
Frame 6 has been transmitted.
Frame 7 has been transmitted.

Please enter the last Acknowledgement received.


2
Frame 2 has been transmitted.
Frame 3 has been transmitted.
Frame 4 has been transmitted.
Frame 5 has been transmitted.
Frame 6 has been transmitted.
Frame 7 has been transmitted.

Please enter the last Acknowledgement received.


8
--------------------------------
Result: Thus the given program is executed and the result is verified

(ii)Selective Repeat Protocol

Aim : To write a program for Selective Repeat Protocol using c

Algorithm:
1. Start.
2. Establish connection (recommended UDP)
3. Accept the window size from the client (should be <=40)
4. Accept the packets from the network layer.
5. Calculate the total frames/windows required.
6. Send the details to the client (total packets, total frames.)
7. Initialize the transmit buffer.
8. Built the frame/window depending on the window size.
9. Transmit the frame.
10. Wait for the acknowledgement frame.
11. Check for the acknowledgement of each packet and repeat the
Process for the packet for which the negative acknowledgement is received.
Else continue as usual.
12. Increment the frame count and repeat steps 7 to 12 until all packets are
Transmitted.
13. Close the connection.
14.Stop.

Program :
//inculsion
#include<iostream>
#include<stdio.h>

#include<sys/types.h>
#include<netinet/in.h>
#include<netdb.h>

#define cls() printf(“33[H33[J”)

//structure definition for designing the packet.


struct frame
{
int packet[40];
};

//structure definition for accepting the acknowledgement.


struct ack
{
int acknowledge[40];
};
int main()
{
int serversocket;
sockaddr_in serveraddr,clientaddr;
socklen_t len;
int windowsize,totalpackets,totalframes,framessend=0,i=0,j=0,k,l,m,n,repacket[40];
ack acknowledgement;
frame f1;
char req[50];
serversocket=socket(AF_INET,SOCK_DGRAM,0);
bzero((char*)&serveraddr,sizeof(serveraddr));
serveraddr.sin_family=AF_INET;
serveraddr.sin_port=htons(5018);
serveraddr.sin_addr.s_addr=INADDR_ANY;
bind(serversocket,(sockaddr*)&serveraddr,sizeof(serveraddr));
bzero((char*)&clientaddr,sizeof(clientaddr));
len=sizeof(clientaddr);

//connection establishment.
printf(“\nWaiting for client connection.\n”);
recvfrom(serversocket,req,sizeof(req),0,(sockaddr*)&clientaddr,&len);
printf(“\nThe client connection obtained.\t%s\n”,req);

//sending request for windowsize.


printf(“\nSending request for window size.\n”);
sendto(serversocket,”REQUEST FOR WINDOWSIZE.”,sizeof(“REQUEST FOR
WINDOWSIZE.”),0,(sockaddr*)&clientaddr,sizeof(clientaddr));

//obtaining windowsize.
printf(“\nWaiting for the windowsize.\n”);
recvfrom(serversocket,(char*)&windowsize,sizeof(windowsize),0,
(sockaddr*)&clientaddr,&len);
cls( );
printf(“\nThe windowsize obtained as:\t%d\n”,windowsize);
printf(“\nObtaining packets from network layer.\n”);
printf(“\nTotal packets obtained:\t%d\n”,(totalpackets=windowsize*5));
printf(“\nTotal frames or windows to be transmitted:\t%d\n”,(totalframes=5));
//sending details to client.
printf(“\nSending total number of packets.\n”);
sendto(serversocket,(char*)&totalpackets,sizeof(totalpackets),0,
(sockaddr*)&clientaddr,sizeof(clientaddr));
recvfrom(serversocket,req,sizeof(req),0,(sockaddr*)&clientaddr,&len);
printf(“\nSending total number of frames.\n”);
sendto(serversocket,(char*)&totalframes,sizeof(totalframes),0,
(sockaddr*)&clientaddr,sizeof(clientaddr));
recvfrom(serversocket,req,sizeof(req),0,(sockaddr*)&clientaddr,&len);
printf(“\nPRESS ENTER TO START THE PROCESS.\n”);
fgets(req,2,stdin);
cls( );

j=0;
l=0; //starting the process of sending
while( l<totalpackets)
{
//initialising the transmit buffer.
bzero((char*)&f1,sizeof(f1));
printf(“\nInitialising the transmit buffer.\n”);
printf(“\nThe frame to be send is %d with packets:\t”,framessend);
//Builting the frame.
for(m=0;m<j;m++)
{
//including the packets for which negative acknowledgement was received.
printf(“%d “,repacket[m]);
f1.packet[m]=repacket[m];
}
while(j<windowsize && i<totalpackets)
{
printf(“%d “,i);
f1.packet[j]=i;
i++;
j++;
}
printf(“\nSending frame %d\n”,framessend);
//sending the frame.
sendto(serversocket,(char*)&f1,sizeof(f1),0,(sockaddr*)&clientaddr,sizeof(clientaddr));
//Waiting for the acknowledgement.
printf(“\nWaiting for the acknowledgement.\n”);
recvfrom(serversocket,(char*)&acknowledgement,sizeof(acknowledgement),0,
(sockaddr*)&clientaddr,&len);
cls();
//Checking acknowledgement of each packet.
j=0;
k=0;
m=0;
n=l;
while(m<windowsize && n<totalpackets)
{
if(acknowledgement.acknowledge[m]==-1)
{
printf(“\nNegative acknowledgement received for packet: %d\n”,f1.packet[m]);
k=1;
repacket[j]=f1.packet[m];
j++;
}
else
{
l++;
}
m++;
n++;
}

if(k==0)
{
printf(“\nPositive acknowledgement received for all packets within the frame: %d\
n”,framessend);
}

framessend++;
printf(“\nPRESS ENTER TO PROCEED……\n”);
fgets(req,2,stdin);
cls();
}

printf(“\nAll frames send successfully.\n\nClosing connection with the client.\n”);


close(serversocket);
}

Output
Waiting for Client Connection
The Client Connection Obtained : HI I AM CLIENT
Sending Request for window size
Waiting for the window size
The window size obtained as : 2
Obtaining Packet from the Network layer
Total Packets obtained : 10
Total frames or Windows to be transmitted:5
Sending Total number of Packets
Sending Total number of frames

Result : Thus the Program is executed and the result is verified


(5)Implentation of Distance Vector Routing (information routing Protocol) Bellman Ford
Algorithm

Aim : To write a program to Implementation of distance vector routing (information routing


protocol ) Bellman ford Algorithm
*/
#include<stdio.h>
struct node
{
unsigned dist[20];
unsigned from[20];
}rt[10];
int main()
{
int costmat[20][20];
int nodes,i,j,k,count=0;
printf("\nEnter the number of nodes : ");
scanf("%d",&nodes);//Enter the nodes
printf("\nEnter the cost matrix :\n");
for(i=0;i<nodes;i++)
{
for(j=0;j<nodes;j++)
{
scanf("%d",&costmat[i][j]);
costmat[i][i]=0;
rt[i].dist[j]=costmat[i][j];//initialise the distance equal to cost matrix
rt[i].from[j]=j;
}
}
do
{
count=0;
for(i=0;i<nodes;i++)//We choose arbitary vertex k and we calculate the direct distance
from the node i to k using the cost matrix
//and add the distance from k to node j
for(j=0;j<nodes;j++)
for(k=0;k<nodes;k++)
if(rt[i].dist[j]>costmat[i][k]+rt[k].dist[j])
{//We calculate the minimum distance
rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];
rt[i].from[j]=k;
count++;
}
}while(count!=0);
for(i=0;i<nodes;i++)
{
printf("\n\n For router %d\n",i+1);
for(j=0;j<nodes;j++)
{
printf("\t\nnode %d via %d Distance %d ",j+1,rt[i].from[j]+1,rt[i].dist[j]);
}
}
printf("\n\n");
getch();
}
/*
A sample run of the program works as:-
Enter the number of nodes :
3
Enter the cost matrix:
027
201
710
For router 1
node 1 via 1 Distance 0
node 2 via 2 Distance 2
node 3 via 3 Distance 3
For router 2
node 1 via 1 Distance 2
node 2 via 2 Distance 0
node 3 via 3 Distance 1
For router 3
node 1 via 1 Distance 3
node 2 via 2 Distance 1
node 3 via 3 Distance 0
*/
Result: Thus the given program is executed and the result is verified
(6)Implementation of link state routing using Dijkstras Algorithm

Aim : To write a program to Implementation of link state routing using Dijkstras Algorithm
Algorithm
1) Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest
Path tree, i.e., whose minimum distance from source is calculated and finalized. Initially,
this set is empty.
2) Assign a distance value to all vertices in the input graph. Initialize all distance values as
INFINITE. Assign distance value as 0 for the source vertex so that it is picked first.
3) While sptSet doesn’t include all vertices
a) Pick a vertex u which is not there in sptSet and has minimum distance value.
b) Include u to sptSet.
c) Update distance value of all adjacent vertices of u. To update the distance values, iterate
through all adjacent vertices. For every adjacent vertex v, if sum of distance value of u
(from source) and weight of edge u-v, is less than the distance value of v, then update the
distance value of v.

Dijkstra’s Algorithm Program in C

#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10

void dijkstra(int G[MAX][MAX],int n,int startnode);


int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
printf("\nEnter the starting node:");
scanf("%d",&u);
dijkstra(G,n,u);
return 0;
}

void dijkstra(int G[MAX][MAX],int n,int startnode)


{

int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count, mindistance, nextnode ,I ,j;
//pred[ ] stores the predecessor of each node
//count gives the number of nodes seen so far
//create the cost matrix
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];
//initialize pred[],distance[] and visited[]
for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
{
mindistance=INFINITY;
//nextnode gives the node at minimum distance
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}
//check if a better path exists through nextnode
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}

//print the path and distance of each node


for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);
j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}
Result: Thus the given program is executed and the result is verified
(7)Data encryption and decryption using Data Encryption Standard algorithm using c program

Aim: To write a Program for data encryption and decryption using data encryption standard
algorithm using C Program
Algorithm:
(i) Write the Program using C Language
(ii) Enter the Program
(iii) Run & Execute the Program
(iv) Correct the errors
(v) Feed the Input and get the output
(vi)Stop the program
Program:

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <time.h>
int IP[] =
{
58, 50, 42, 34, 26, 18, 10, 2,
60, 52, 44, 36, 28, 20, 12, 4,
62, 54, 46, 38, 30, 22, 14, 6,
64, 56, 48, 40, 32, 24, 16, 8,
57, 49, 41, 33, 25, 17, 9, 1,
59, 51, 43, 35, 27, 19, 11, 3,
61, 53, 45, 37, 29, 21, 13, 5,
63, 55, 47, 39, 31, 23, 15, 7
};
int E[] =
{
32, 1, 2, 3, 4, 5,
4, 5, 6, 7, 8, 9,
8, 9, 10, 11, 12, 13,
12, 13, 14, 15, 16, 17,
16, 17, 18, 19, 20, 21,
20, 21, 22, 23, 24, 25,
24, 25, 26, 27, 28, 29,
28, 29, 30, 31, 32, 1
};
int P[] =
{
16, 7, 20, 21,
29, 12, 28, 17,
1, 15, 23, 26,
5, 18, 31, 10,
2, 8, 24, 14,
32, 27, 3, 9,
19, 13, 30, 6,
22, 11, 4, 25
};

int FP[] =
{
40, 8, 48, 16, 56, 24, 64, 32,
39, 7, 47, 15, 55, 23, 63, 31,
38, 6, 46, 14, 54, 22, 62, 30,
37, 5, 45, 13, 53, 21, 61, 29,
36, 4, 44, 12, 52, 20, 60, 28,
35, 3, 43, 11, 51, 19, 59, 27,
34, 2, 42, 10, 50, 18, 58, 26,
33, 1, 41, 9, 49, 17, 57, 25
};
int S1[4][16] =
{
14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7,
0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8,
4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0,
15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13
};
int S2[4][16] =
{
15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10,
3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5,
0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15,
13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9
};
int S3[4][16] =
{
10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8,
13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1,
13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7,
1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12
};
int S4[4][16] =
{
7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15,
13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9,
10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4,
3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14
};
int S5[4][16] =
{
2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9,
14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6,
4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14,
11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3
};
int S6[4][16] =
{
12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11,
10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8,
9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6,
4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13
};
int S7[4][16]=
{
4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1,
13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6,
1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2,
6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12
};
int S8[4][16]=
{
13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7,
1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2,
7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8,
2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11
};
int PC1[] =
{
57, 49, 41, 33, 25, 17, 9,
1, 58, 50, 42, 34, 26, 18,
10, 2, 59, 51, 43, 35, 27,
19, 11, 3, 60, 52, 44, 36,
63, 55, 47, 39, 31, 23, 15,
7, 62, 54, 46, 38, 30, 22,
14, 6, 61, 53, 45, 37, 29,
21, 13, 5, 28, 20, 12, 4
};
int PC2[] =
{
14, 17, 11, 24, 1, 5,
3, 28, 15, 6, 21, 10,
23, 19, 12, 4, 26, 8,
16, 7, 27, 20, 13, 2,
41, 52, 31, 37, 47, 55,
30, 40, 51, 45, 33, 48,
44, 49, 39, 56, 34, 53,
46, 42, 50, 36, 29, 32
};
int SHIFTS[] = { 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 };
FILE* out;
int LEFT[17][32], RIGHT[17][32];
int IPtext[64];
int EXPtext[48];
int XORtext[48];
int X[8][6];
int X2[32];
int R[32];
int key56bit[56];
int key48bit[17][48];
int CIPHER[64];
int ENCRYPTED[64];

void expansion function (int pos, int text)


{
for (int i = 0; i < 48; i++)
{
if (E[i] == pos + 1) {
EXPtext[i] = text;
}
}
}
int initialPermutation(int pos, int text)
{
int i;
for (i = 0; i < 64; i++)
{
if (IP[i] == pos + 1) {
break;
}
}
IPtext[i] = text;
}
int F1(int i)
{
int r, c, b[6];

for (int j = 0; j < 6; j++) {


b[j] = X[i][j];
}
r = b[0] * 2 + b[5];
c = 8 * b[1] + 4 * b[2] + 2 * b[3] + b[4];
if (i == 0) {
return S1[r][c];
}
else if (i == 1) {
return S2[r][c];
}
else if (i == 2) {
return S3[r][c];
}
else if (i == 3) {
return S4[r][c];
}
else if (i == 4) {
return S5[r][c];
}
else if (i == 5) {
return S6[r][c];
}
else if (i == 6) {
return S7[r][c];
}
else if (i == 7) {
return S8[r][c];
}
}

int XOR(int a, int b) {


return (a ^ b);
}
int ToBits(int value)
{
int k, j, m;
static int i;
if (i % 32 == 0) {
i = 0;
}

for (j = 3; j >= 0; j--)


{
m = 1 << j;
k = value & m;
if (k == 0) {
X2[3 - j + i] = '0' – 48;
}
else {
X2[3 - j + i] = '1' – 48;
}
}

i = i + 4;
}
int SBox(int XORtext[])
{
int k = 0;
for (int i = 0; i < 8; i++)
{
for (int j = 0; j < 6; j++) {
X[i][j] = XORtext[k++];
}
}
int value;
for (int i = 0; i < 8; i++)
{
value = F1(i);
ToBits(value);
}
}
int PBox(int pos, int text)
{
int i;
for (i = 0; i < 32; i++)
{
if (P[i] == pos + 1) {
break;
}
}
R[i] = text;
}
void cipher(int Round, int mode)
{
for (int i = 0; i < 32; i++) {
expansion_function(i, RIGHT[Round – 1][i]);
}
for (int i = 0; i < 48; i++)
{
if (mode == 0) {
XORtext[i] = XOR(EXPtext[i], key48bit[Round][i]);
}
else {
XORtext[i] = XOR(EXPtext[i], key48bit[17 – Round][i]);
}
}
SBox(XORtext);
for (int i = 0; i < 32; i++) {
PBox(i, X2[i]);
}

for (int i = 0; i < 32; i++) {


RIGHT[Round][i] = XOR(LEFT[Round – 1][i], R[i]);
}
}
void final Permutation(int pos, int text)
{
int i;
for (i = 0; i < 64; i++)
{
if (FP[i] == pos + 1) {
break;
}
}
ENCRYPTED[i] = text;
}

void convert To Binary(int n)


{
int k, m;
for (int i = 7; i >= 0; i--)
{
m = 1 << i;
k = n & m;
if (k == 0) {
fprintf(out, "0");
}
else {
fprintf(out, "1");
}
}
}

int convert Char To Bit(long int n)


{
FILE* inp = fopen("input.txt", "rb");
out = fopen("bits.txt", "wb+");
char ch;
int i = n * 8;

while (i)
{
ch = fgetc(inp);
if (ch == -1) {
break;
}
i--;
convertToBinary(ch);
}
fclose(out);
fclose(inp);
}

void Encryption(long int plain[])


{
out = fopen("cipher.txt", "ab+");
for (int i = 0; i < 64; i++) {
initialPermutation(i, plain[i]);
}
for (int i = 0; i < 32; i++) {
LEFT[0][i] = IPtext[i];
}

for (int i = 32; i < 64; i++) {


RIGHT[0][i – 32] = IPtext[i];
}
for (int k = 1; k < 17; k++)
{
cipher(k, 0);

for (int i = 0; i < 32; i++)


LEFT[k][i] = RIGHT[k – 1][i];
}
for (int i = 0; i < 64; i++)
{
if (i < 32) {
CIPHER[i] = RIGHT[16][i];
}
else {
CIPHER[i] = LEFT[16][i – 32];
}
finalPermutation(i, CIPHER[i]);
}
for (int i = 0; i < 64; i++) {
fprintf(out, "%d", ENCRYPTED[i]);
}
fclose(out);
}
void Decryption(long int plain[])
{
out = fopen("decrypted.txt", "ab+");
for (int i = 0; i < 64; i++) {
initialPermutation(i, plain[i]);
}

for (int i = 0; i < 32; i++) {


LEFT[0][i] = IPtext[i];
}
for (int i = 32; i < 64; i++) {
RIGHT[0][i – 32] = IPtext[i];
}
for (int k = 1; k < 17; k++)
{
cipher(k, 1);
for (int i = 0; i < 32; i++) {
LEFT[k][i] = RIGHT[k – 1][i];
}
}
for (int i = 0; i < 64; i++)
{
if (i < 32) {
CIPHER[i] = RIGHT[16][i];
} else {
CIPHER[i] = LEFT[16][i – 32];
}
Final Permutation(i, CIPHER[i]);
}
for (int i = 0; i < 64; i++) {
fprintf(out, "%d", ENCRYPTED[i]);
}
fclose(out);
}
void convert To Bits(int ch[])
{
int value = 0;
for (int i = 7; i >= 0; i--) {
value += (int)pow(2, i) * ch[7 – i];
}
fprintf(out, "%c", value);
}
int bittochar()
{
out = fopen("result.txt", "ab+");
for (int i = 0; i < 64; i = i + 8) {
convertToBits(&ENCRYPTED[i]);
}
fclose(out);
}
void key56to48(int round, int pos, int text)
{
int i;
for (i = 0; i < 56; i++)
{
if (PC2[i] == pos + 1) {
break;
}
}
key48bit[round][i] = text;
}
int key 64to56(int pos, int text)
{
int i;
for (i = 0; i < 56; i++)
{
if (PC1[i] == pos + 1) {
break;
}
}
key56bit[i] = text;
}
void key64to48(unsigned int key[])
{
int k, backup[17][2];
int CD[17][56];
int C[17][28], D[17][28];
for (int i = 0; i < 64; i++) {
key64to56(i, key[i]);
}
for (int i = 0; i < 56; i++)
{
if (i < 28) {
C[0][i] = key56bit[i];
}
else {
D[0][i – 28] = key56bit[i];
}
}
for (int x = 1; x < 17; x++)
{
int shift = SHIFTS[x – 1];
for (int i = 0; i < shift; i++) {
backup[x - 1][i] = C[x – 1][i];
}
for (int i = 0; i < (28 – shift); i++) {
C[x][i] = C[x – 1][i + shift];
}
k = 0;
for (int i = 28 – shift; i < 28; i++) {
C[x][i] = backup[x – 1][k++];
}
for (int i = 0; i < shift; i++) {
backup[x - 1][i] = D[x – 1][i];
}
for (int i = 0; i < (28 – shift); i++) {
D[x][i] = D[x – 1][i + shift];
}
k = 0;
for (int i = 28 – shift; i < 28; i++) {
D[x][i] = backup[x – 1][k++];
}
}
for (int j = 0; j < 17; j++)
{
for (int i = 0; i < 28; i++) {
CD[j][i] = C[j][i];
}
for (int i = 28; i < 56; i++) {
CD[j][i] = D[j][i – 28];
}
}
for (int j = 1; j < 17; j++)
{
for (int i = 0; i < 56; i++) {
key56to48(j, i, CD[j][i]);
}
}
}
void decrypt(long int n)
{
FILE* in = fopen("cipher.txt", "rb");
long int plain[n * 64];
int i = -1;
char ch;
while (!feof(in))
{
ch = getc(in);
plain[++i] = ch – 48;
}
for (int i = 0; i < n; i++)
{
Decryption(plain + i * 64);
bittochar();
}
fclose(in);
}
void encrypt(long int n)
{
FILE* in = fopen("bits.txt", "rb");
long int plain[n * 64];
int i = -1;
char ch;
while (!feof(in))
{
ch = getc(in);
plain[++i] = ch – 48;
}
for (int i = 0; i < n; i++) {
Encryption(plain + 64 * i);
}
fclose(in);
}
void create16Keys()
{
FILE* pt = fopen("key.txt", "rb");
unsigned int key[64];
int i = 0, ch;
while (!feof(pt))
{
ch = getc(pt);
key[i++] = ch – 48;
}
key64to48(key);
fclose(pt);
}
long int findFileSize()
{
FILE* inp = fopen("input.txt", "rb");
long int size;
if (fseek(inp, 0L, SEEK_END)) {
perror("fseek() failed");
}
// size will contain number of chars in the input file.
else {
size = ftell(inp);
}
fclose(inp);
return size;
}
int main()
{
// destroy contents of these files (from previous runs, if any)
out = fopen("result.txt", "wb+");
fclose(out);
out = fopen("decrypted.txt", "wb+");
fclose(out);
out = fopen("cipher.txt", "wb+");
fclose(out);
create16Keys();
long int n = findFileSize() / 8;
convertCharToBit(n);
encrypt(n);
decrypt(n);
return 0;
}

OUTPUT

result.txt – IT WILL CONTAIN OUR DECRYPTED TEXT.

TEMP FILES:

bits.txt – IT WILL CONTAIN OUR PLAIN TEXT CONVERTED IN BITS.


cipher.txt – IT WILL CONTAIN OUR ENCRYPTED TEXT IN BITS.
decrypted.txt – IT WILL CONTAIN OUR DECRYPTED TEXT IN BITS (SAME AS bits.txt IN CONTENT)

Result: Thus the given program is executed and the result is verified
(8)Data Encryption & Decryption using RSA Algorithm

Aim : To write a Program for data encryption & decryption using RSA Algorithm
1. Ask the user to enter two prime numbers and validate them.
2. Store the prime numbers in variables.
3. Compute n = pq.
4. Compute λ(n) = (p – 1)(q – 1).
5. Choose a random number e as a relatively prime number to λ(n) and 1 < e < λ(n).
6. Compute d = e-1 mod λ(n).
7. Print the public and private keys.
8. Ask the user to enter a message and store it in a variable.
9. Encrypt the message using the public key.
10. Decrypt the message using the private key.
11. Print the encrypted and decrypted message.

program to Implement the RSA Algorithm

1. #include<stdio.h>
2. #include<conio.h>
3. #include<stdlib.h>
4. #include<math.h>
5. #include<string.h>
6. long int p, q, n, t, flag, e[100], d[100], temp[100], j, m[100], en[100], i;
7. char msg[100];
8. int prime(long int);
9. void ce();
10. long int cd(long int);
11. void encrypt();
12. void decrypt();
13. void main()
14. {
15. printf("\nENTER FIRST PRIME NUMBER\n");
16. scanf("%d", &p);
17. flag = prime(p);
18. if (flag == 0)
19. {
20. printf("\nWRONG INPUT\n");
21. getch();
22. exit(1);
23. }
24. printf("\nENTER ANOTHER PRIME NUMBER\n");
25. scanf("%d", &q);
26. flag = prime(q);
27. if (flag == 0 || p == q)
28. {
29. printf("\nWRONG INPUT\n");
30. getch();
31. exit(1);
32. }
33. printf("\nENTER MESSAGE\n");
34. fflush(stdin);
35. scanf("%s", msg);
36. for (i = 0; msg[i] != NULL; i++)
37. m[i] = msg[i];
38. n = p * q;
39. t = (p - 1) * (q - 1);
40. ce();
41. printf("\nPOSSIBLE VALUES OF e AND d ARE\n");
42. for (i = 0; i < j - 1; i++)
43. printf("\n%ld\t%ld", e[i], d[i]);
44. encrypt();
45. decrypt();
46. }
47. int prime(long int pr)
48. {
49. int i;
50. j = sqrt(pr);
51. for (i = 2; i <= j; i++)
52. {
53. if (pr % i == 0)
54. return 0;
55. }
56. return 1;
57. }
58. void ce()
59. {
60. int k;
61. k = 0;
62. for (i = 2; i < t; i++)
63. {
64. if (t % i == 0)
65. continue;
66. flag = prime(i);
67. if (flag == 1 && i != p && i != q)
68. {
69. e[k] = i;
70. flag = cd(e[k]);
71. if (flag > 0)
72. {
73. d[k] = flag;
74. k++;
75. }
76. if (k == 99)
77. break;
78. }
79. }
80. }
81. long int cd(long int x)
82. {
83. long int k = 1;
84. while (1)
85. {
86. k = k + t;
87. if (k % x == 0)
88. return (k / x);
89. }
90. }
91. void encrypt()
92. {
93. long int pt, ct, key = e[0], k, len;
94. i = 0;
95. len = strlen(msg);
96. while (i != len)
97. {
98. pt = m[i];
99. pt = pt - 96;
100. k = 1;
101. for (j = 0; j < key; j++)
102. {
103. k = k * pt;
104. k = k % n;
105. }
106. temp[i] = k;
107. ct = k + 96;
108. en[i] = ct;
109. i++;
110. }
111. en[i] = -1;
112. printf("\nTHE ENCRYPTED MESSAGE IS\n");
113. for (i = 0; en[i] != -1; i++)
114. printf("%c", en[i]);
115. }
116. void decrypt()
117. {
118. long int pt, ct, key = d[0], k;
119. i = 0;
120. while (en[i] != -1)
121. {
122. ct = temp[i];
123. k = 1;
124. for (j = 0; j < key; j++)
125. {
126. k = k * ct;
127. k = k % n;
128. }
129. pt = k + 96;
130. m[i] = pt;
131. i++;
132. }
133. m[i] = -1;
134. printf("\nTHE DECRYPTED MESSAGE IS\n");
135. for (i = 0; m[i] != -1; i++)
136. printf("%c", m[i]);
137. }
Runtime Test Cases
In this case, we enter two prime numbers “7” and “19” and then use the RSA algorithm to
encrypt and decrypt a message.

$ gcc RSA.c
$ ./a.out

ENTER FIRST PRIME NUMBER: 7

ENTER ANOTHER PRIME NUMBER: 19

ENTER MESSAGE: Dharmendra

POSSIBLE VALUES OF e AND d ARE


5 65
11 59
13 25
17 89
23 47
29 41
31 7
37 73
41 29
THE ENCRYPTED MESSAGE IS
=’a…º¢É½…a
THE DECRYPTED MESSAGE IS
Dharmendra
Result: Thus the given program is executed and the result is verified
(9)Implement Client Server model using FTP protocol

Aim : To write a Program to implement client server model using FTP protocol
FTP server
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

/*for getting file size using stat()*/


#include<sys/stat.h>

/*for sendfile()*/
#include<sys/sendfile.h>

/*for O_RDONLY*/
#include<fcntl.h>

int main(int argc,char *argv[])


{
struct sockaddr_in server, client;
struct stat obj;
int sock1, sock2;
char buf[100], command[5], filename[20];
int k, i, size, len, c;
int filehandle;
sock1 = socket(AF_INET, SOCK_STREAM, 0);
if(sock1 == -1)
{
printf("Socket creation failed");
exit(1);
}
server.sin_port = atoi(argv[1]);
server.sin_addr.s_addr = 0;
k = bind(sock1,(struct sockaddr*)&server,sizeof(server));
if(k == -1)
{
printf("Binding error");
exit(1);
}
k = listen(sock1,1);
if(k == -1)
{
printf("Listen failed");
exit(1);
}
len = sizeof(client);
sock2 = accept(sock1,(struct sockaddr*)&client, &len);
i = 1;
while(1)
{
recv(sock2, buf, 100, 0);
sscanf(buf, "%s", command);
if(!strcmp(command, "ls"))
{
system("ls >temps.txt");
i = 0;
stat("temps.txt",&obj);
size = obj.st_size;
send(sock2, &size, sizeof(int),0);
filehandle = open("temps.txt", O_RDONLY);
sendfile(sock2,filehandle,NULL,size);
}
else if(!strcmp(command,"get"))
{
sscanf(buf, "%s%s", filename, filename);
stat(filename, &obj);
filehandle = open(filename, O_RDONLY);
size = obj.st_size;
if(filehandle == -1)
size = 0;
send(sock2, &size, sizeof(int), 0);
if(size)
send file(sock2, filehandle, NULL, size);

}
else if(!strcmp(command, "put"))
{
int c = 0, len;
char *f;
sscanf(buf+strlen(command), "%s", filename);
recv(sock2, &size, sizeof(int), 0);
i = 1;
while(1)
{
filehandle = open(filename, O_CREAT | O_EXCL | O_WRONLY, 0666);
if(filehandle == -1)
{
sprintf(filename + strlen(filename), "%d", i);
}
else
break;
}
f = malloc(size);
recv(sock2, f, size, 0);
c = write(filehandle, f, size);
close(filehandle);
send(sock2, &c, sizeof(int), 0);
}
else if(!strcmp(command, "pwd"))
{
system("pwd>temp.txt");
i = 0;
FILE*f = fopen("temp.txt","r");
while(!feof(f))
buf[i++] = fgetc(f);
buf[i-1] = '\0';
fclose(f);
send(sock2, buf, 100, 0);
}
else if(!strcmp(command, "cd"))
{
if(chdir(buf+3) == 0)
c = 1;
else
c = 0;
send(sock2, &c, sizeof(int), 0);
}

else if(!strcmp(command, "bye") || !strcmp(command, "quit"))


{
printf("FTP server quitting..\n");
i = 1;
send(sock2, &i, sizeof(int), 0);
exit(0);
}
}
return 0;
}

/*FTP Client*/

#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdio.h>
#include <stdlib.h>

/*for getting file size using stat( )*/


#include<sys/stat.h>

/*for sendfile()*/
#include<sys/sendfile.h>

/*for O_RDONLY*/
#include<fcntl.h>

int main(int argc,char *argv[])


{
struct sockaddr_in server;
struct stat obj;
int sock;
int choice;
char buf[100], command[5], filename[20], *f;
int k, size, status;
int filehandle;
sock = socket(AF_INET, SOCK_STREAM, 0);
if(sock == -1)
{
printf("socket creation failed");
exit(1);
}
server.sin_family = AF_INET;
server.sin_port = atoi(argv[1]);
server.sin_addr.s_addr = 0;
k = connect(sock,(struct sockaddr*)&server, sizeof(server));
if(k == -1)
{
printf("Connect Error");
exit(1);
}
int i = 1;
while(1)
{
printf("Enter a choice:\n1- get\n2- put\n3- pwd\n4- ls\n5- cd\n6- quit\n");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter filename to get: ");
scanf("%s", filename);
strcpy(buf, "get ");
strcat(buf, filename);
send(sock, buf, 100, 0);
recv(sock, &size, sizeof(int), 0);
if(!size)
{
printf("No such file on the remote directory\n\n");
break;
}
f = malloc(size);
recv(sock, f, size, 0);
while(1)
{
filehandle = open(filename, O_CREAT | O_EXCL | O_WRONLY, 0666);
if(filehandle == -1)
{
sprintf(filename + strlen(filename), "%d", i);
//needed only if same directory is used for both server and client
}
else break;
}
write(filehandle, f, size, 0);
close(filehandle);
strcpy(buf, "cat ");
strcat(buf, filename);
system(buf);
break;
case 2:
printf("Enter filename to put to server: ");
scanf("%s", filename);
filehandle = open(filename, O_RDONLY);
if(filehandle == -1)
{
printf("No such file on the local directory\n\n");
break;
}
strcpy(buf, "put ");
strcat(buf, filename);
send(sock, buf, 100, 0);
stat(filename, &obj);
size = obj.st_size;
send(sock, &size, sizeof(int), 0);
sendfile(sock, filehandle, NULL, size);
recv(sock, &status, sizeof(int), 0);
if(status)
printf("File stored successfully\n");
else
printf("File failed to be stored to remote machine\n");
break;
case 3:
strcpy(buf, "pwd");
send(sock, buf, 100, 0);
recv(sock, buf, 100, 0);
printf("The path of the remote directory is: %s\n", buf);
break;
case 4:
strcpy(buf, "ls");
send(sock, buf, 100, 0);
recv(sock, &size, sizeof(int), 0);
f = malloc(size);
recv(sock, f, size, 0);
filehandle = creat("temp.txt", O_WRONLY);
write(filehandle, f, size, 0);
close(filehandle);
printf("The remote directory listing is as follows:\n");
system("cat temp.txt");
break;
case 5:
strcpy(buf, "cd ");
printf("Enter the path to change the remote directory: ");
scanf("%s", buf + 3);
send(sock, buf, 100, 0);
recv(sock, &status, sizeof(int), 0);
if(status)
printf("Remote directory successfully changed\n");
else
printf("Remote directory failed to change\n");
break;
case 6:
strcpy(buf, "quit");
send(sock, buf, 100, 0);
recv(sock, &status, 100, 0);
if(status)
{
printf("Server closed\nQuitting..\n");
exit(0);
}
printf("Server failed to close connection\n");
}
}
}

Result: Thus the given program is executed and the result is verified
(10)Implement and perform the operation of CSMA/CD and CSMA/CA

Aim: To write a Program to perform the operation of CSMA/CD and CSMA/CA

Algorithm:
(i) Write the Program using C Language
(ii) Enter the Program
(iii) Run & Execute the Program
(iv) Correct the errors
(v) Feed the Input and get the output
(vi)Stop the program

Program:
#include "template.h"
#include "random.h"
#include "channel.h"
#include "mac-csma.h"
static class MacCsmaClass : public TclClass {
public: MacCsmaClass() : TclClass("Mac/Csma") {}
TclObject* create(int, const char*const*) {
return (new MacCsma);
} } class_mac_csma;

static class MacCsmaCdClass : public TclClass {


public: MacCsmaCdClass() : TclClass("Mac/Csma/Cd") {}
TclObject* create(int, const char*const*) {
return (new MacCsmaCd);
} } class_mac_csma_cd;

static class MacCsmaCaClass : public TclClass {


public:
MacCsmaCaClass() : TclClass("Mac/Csma/Ca") {}
TclObject* create(int, const char*const*) {
return (new MacCsmaCa);
} } class_mac_csma_ca;

void MacHandlerEoc::handle(Event* e)
{
mac_->endofContention((Packet*)e);
}
MacCsma::MacCsma() : txstart_(0), rtx_(0), csense_(1), hEoc_(this)
{
bind_time("ifs_", &ifs_);
bind_time("slotTime_", &slotTime_);
bind("cwmin_", &cwmin_);
bind("cwmax_", &cwmax_);
bind("rtxLimit_", &rtxLimit_);
bind("csense_", &csense_);
cw_ = cwmin_;
}

void MacCsma::resume(Packet* p)
{
Scheduler& s = Scheduler::instance();
s.schedule(callback_, &intr_, ifs_ + slotTime_ * cwmin_);
if (p != 0)
drop(p);
callback_ = 0;
state(MAC_IDLE);
rtx_ = 0;
cw_ = cwmin_;
}

void MacCsma::send(Packet* p)
{
Scheduler& s = Scheduler::instance();
double delay = channel_->txstop() + ifs_ - s.clock();

static const double EPS= 1.0e-12; //seems appropriate (less than nanosec)
if (csense_ && delay > EPS)
s.schedule(&hSend_, p, delay + 0.000001);
else {
txstart_ = s.clock();
channel_->contention(p, &hEoc_);
}
Result: Thus the given program is executed and the result is verified
11.Implement and realize the Network Topology - Star, Bus and Ring using NS2.

AIM: To Implement and realize the bus network topology using NS2 through simulation.
Hardware / Software Requirements: NS-2
ALGORITHM:
1. Create a simulator object
2. Define different colors for different data flows
3. Open a name trace file and define finish procedure then close the trace file, and execute
name on trace file.
4. Create five nodes that forms a network numbered from 0 to 4
5. Create duplex links between the nodes and add Orientation to the nodes for setting a LAN
topology
6. Setup TCP Connection between n(1) and n(3)
7. Apply CBR Traffic over TCP.
8. Schedule events and run the program

Program:
#Creating five nodes
set node1 [$ns node]
setnode2 [$ns node]
set node3 [$ns node]
setnode4 [$ns node]
set node5 [$ns node]
#Creating Lan connection between the nodes
set lan0 [$ns newLan “$node1 $node2$node3 $node4 $node5” 0.7Mb 20ms LL Queue/FQ MAC
/Csma/Cd Channel]
#Creating a TCP agent and attaching it to node 1
set tcp0 [new Agent/TCP]
$tcp0 set class_ 1
$ns attach-agent $node1 $tcp0
#Creating a TCP Sink agent for TCP and attaching it to node 3
set sink0 [new Agent/TCPSink]
$ns attach-agent $node3 $sink0
#Connecting the traffic sources with the traffic sink
$ns connect $tcp0 $sink0
# Creating a CBR traffic source and attach it to tcp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$ cbr0 set interval_ 0.05
$cbr0 attach-agent $tcp0
#Schedule events for the CBR agents
$ns at 0.5 “$cbr0 start time”
$ ns at 5.5 “$cbr0 stop time”
#Here we call the finish procedure after 10 seconds of simulation time
$ns at 10.0 “End”
#Finally run the simulation
$ns run
Here, we have created four nodes and they are linked together using Bus topology. We
have given the overall code for all the parameters used in the construction of bus topology.

(ii) Ring Topology

#Creating six nodes


setnode1 [$ns node]
set node2 [$ns node]
setnode3 [$ns node]
set node4 [$ns node]
setnode5 [$ns node]
set node6 [$ns node]
#Creating links between the nodes
$ ns duplex-link $node1 $node2 1Mb 15ms FQ
$ns duplex-link $node2 $node3 1Mb 15ms FQ
$ ns duplex-link $node3 $node4 1Mb 15ms FQ
$ns duplex-link $node4 $node5 1Mb 15ms FQ
$ ns duplex-link $node5 $node6 1Mb 15ms FQ
$ns duplex-link $node6 $node1 1Mb 15ms FQ\”Forms Ring Topology”
Here, we have created six nodes and are connected using Ring topology. The code may
look similar to the early one, but it shows the difference in terms of its connectivity. All the
nodes are connected in a ring manner, in order to have high data transmission rates.

You might also like