Ns Lab
Ns Lab
To implement the data link layer framing methods bit stuffing using
C language.
SOFTWARE REQUIRED:
• Linux OS – Ubuntu
• C Compiler - gcc
THEORY:
Bit stuffing is a technique used in data transmission to ensure reliable
and accurate synchronization between the sender and receiver. It
involves adding extra bits to a data stream according to specific
rules.For example, let's say the rule is to insert a "0" bit after five
consecutive "1" bits. If the sender's data contains the sequence
"1111101111," the sender would insert an additional "0" bit after the
fifth "1" bit, resulting in "11111001111" before transmitting the data.
The receiver is aware of this bit-stuffing rule and knows to remove
the stuffed bits upon receiving the data.
ALGORITHM:
1. Open C compiler - gcc and type the program for bit stuffing.
2. Initialize the array for transmitted stream with the special bit
pattern 01111110 which indicates the beginning of the frame.
3. Get the bit stream to be transmitted in to the array.
4. Check for five consecutive ones and if they occur, stuff a bit0.
5. Display the data transmitted as it appears on the data line after
appending 01111110 at the end.
6. Display the received bit stream.
7. Run the program.
PROGRAM:
#include <stdio.h>
#include <string.h>
#define FLAG 126
#define ESC 125
void stuff_char(unsigned char c, unsigned char *out, int *out_idx) {
if (c == FLAG || c == ESC) {
out[(*out_idx)++] = ESC;
out[(*out_idx)++] = c ^ 0x20;
} else {
out[(*out_idx)++] = c;
}
}
void bit_stuff(unsigned char *in, int in_len, unsigned char *out, int
*out_len) {
int i;
int out_idx = 0;
int ones_count = 0;
out[out_idx++] = FLAG;
for (i = 0; i < in_len; i++) {
if (in[i] == 1) {
ones_count++;
} else
{
ones_count = 0;
}
if (ones_count == 6) {
stuff_char(0, out, &out_idx);
ones_count = 0;
}
stuff_char(in[i], out, &out_idx);
}
out[out_idx++] = FLAG;
*out_len = out_idx;
}
int main()
{
unsigned char in[100];
printf("Enter input data: ");
fgets(in, sizeof(in), stdin);
int in_len = strlen(in) - 1;
unsigned char out[2 * in_len];
int out_len;
unsigned char binary_in[in_len];
for (int i = 0; i < in_len; i++) {
if (in[i] == '0') {
binary_in[i] = 0;
} else if (in[i] == '1') {
binary_in[i] = 1;
} else {
printf("Invalid input: %c\n", in[i]);
return 1;
}
}
bit_stuff(binary_in, in_len, out, &out_len);
printf("Input data: %s\n", in);
printf("Output data:\n");
for (int i = 0; i < out_len; i++) {
printf("%d ", out[i]);
}
printf("\n");
}
printf("\n");
return 0;
}
OUTPUT:
Fig no: 1a.1BIT STUFFING
RESULT:
Thus, the data link layer framing methods bit stuffing
using C language is implemented.
AIM:
To implement the data link layer framing methods character
stuffing (bytes stuffing) using C language.
SOFTWARE REQUIRED:
• Linux OS – Ubuntu
• C Compiler - gcc
THEORY:
Byte stuffing is a technique used in data transmission to ensure
reliable and accurate synchronization between the sender and
receiver, particularly in protocols that operate at the byte level.
In byte stuffing, extra bytes are added to the data stream based
on specific rules. It is commonly used when there is a need to
transmit control characters or reserved byte sequences within the
actual data. The purpose is to prevent these special bytes from being
mistaken as control characters for framing or signalling purposes.
ALGORITHM:
• Start with an input byte array (input) and its length (input
Length).
• Create an output byte array (output) with a size greater than or
equal to the maximum possible size of the stuffed bytes.
• Define the flag byte and the escape byte values.
• Initialize variables output Index and output Length to 0.
• Iterate through each byte in the input byte array:
• If the byte is equal to the flag byte or the escape byte, add the
escape byte to the output byte array at index output Index.
• If the byte is not equal to the flag byte or the escape byte, add
the byte as it is to the output byte array at index output Index.
• Increment output Index by 1and increment output Length by
1.
• The stuffed bytes are stored in the output byte array to the
length.
PROGRAM:
#include <stdio.h>
#include <string.h>
#define FLAG 126 /* ASCII code for the flag character ~ */
#define ESC 125 /* ASCII code for the escape character } */
/* Function to stuff a flag or escape character */
void stuff_char(unsigned char c, unsigned char *out, int *out_idx) {
if (c == FLAG || c == ESC) {
out[(*out_idx)++] = ESC;
out[(*out_idx)++] = c ^ 0x20;
} else {
out[(*out_idx)++] = c;
}
}
/* Function to perform character stuffing on a data buffer */
void char_stuff(unsigned char *in, int in_len, unsigned char *out,
int *out_len) {
int i;
int out_idx = 0
/* Start with a flag character */
out[out_idx++] = FLAG;
/* Loop through the input data */
for (i = 0; i < in_len; i++) {
if (in[i] == FLAG || in[i] == ESC) {
/* Stuff the current input character */
stuff_char(in[i], out, &out_idx);
} else {
out[out_idx++] = in[i];
}
}
/* End with another flag character */
out[out_idx++] = FLAG;
/* Set the output length */
*out_len = out_idx;
}
int main() {
unsigned char in[100];
printf("Enter input data: ");
fgets(in, sizeof(in), stdin);
int in_len = strlen(in) - 1;
/* Exclude newline character */
unsigned char out[2 * in_len];
/* Allocate space for worst case */
int out_len;
char_stuff(in, in_len, out, &out_len);
printf("Input data: %s\n", in);
printf("Output data:\n");
for (int i = 0; i < out_len; i++) {
printf("%d ", out[i]);
}
printf("\n");
return 0;
}
OUTPUT:
Fig No: 1b.1 CHARACTER STUFFING.
RESULT:
Thus the implementation of data link layer framing methods
character stuffing (byte stuffing) is executed successfully.
AIM:
To implement error detection longitudinal Redundancy Check
(LRC) using C language.
SOFTWARE REQUIRED:
• Linux OS – Ubuntu
• C Compiler - gcc
THEORY:
LRC is a simple error-checking algorithm used to detect errors in
data transmission. It calculates a parity check value that can be
appended to a block of data to provide a basic level of error
detection.
ALGORITHM:
1. Open Linux software and type the program for error detection.
2. Initialize an LRC variable to zero.
3. Iterate over each byte of data.
4. For each byte, perform an XOR operation between the LRC
variable and the byte value.
5. Update the LRC variable with the result of the XOR operation.
6. After processing all the bytes, the final value of the LRC
variable is the calculated LRC value.
7. Run the program.
PROGRAM:
int main() {
OUTPUT:
Fig no: 2a.1 LRC – WITHOUT ERROR
RESULT:
Thus, the error detection and error correction (LRC) is
implemented successfully.
AIM:
To implement error detection Cyclic Redundancy Check (CRC)
using C language.
SOFTWARE REQUIRED:
• Linux OS – Ubuntu
• C Compiler - gcc
THEORY:
CRC stands for Cyclic Redundancy Check. It is an error-detection
technique used in data communication and storage systems. CRC
allows the detection of errors in data transmission by appending a
calculated checksum to the transmitted data.
ALGORITHM:
• Open Linux software and type the program for error
detection.
• Get the input in the form of bits.
• Append16 zero as redundancy bits.
• Divide the appended data using a divisor polynomial.
• The resulting data should be transmitted to the receiver.
• At the receiver the received data is entered.
• The same process is repeated at the receiver.
• If the remainder is zero there is no error otherwise there is
some error in the received bits
• Run the program.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,j,k=0;
int flag=1,a[16],g[16],r[20],div[16],n,m;
system("clear");
printf("Enter the degree of Generator polynominal:");
scanf("%d",&n);
printf("\nEnter the Generator polynomial:");
for(i=0;i<=n;i++)
scanf("%d",&g[i]);
printf("\nEnter the Degree of Frame to be sent:");
scanf("%d",&m);
printf("\nEnter the Frame:");
for(i=0;i<=m;i++)
scanf("%d",&a[i]);
if(m<n||(g[0]&&g[n])==0)
{
printf("Not a proper generator polynomial\n:");
exit(0);
}
for(i=m+1;i<=m+n;i++)
a[i]=0;
for(j=0;j<=n;j++)
r[j]=a[j];
for(i=n;i<=m+n;i++)
{
if(i>n)
{
for(j=0;j<n;j++)
r[j]=r[j+1];
r[j]=a[i];
}
if(r[0])
div[k++]=1;
else
{
div[k++]=0;
continue;
}
for(j=0;j<=n;j++)
r[j]=r[j]^g[j];
}
printf("\nQuotient is:");
for(j=0;j<k;j++)
printf("%d",div[j]);
printf("\n\nRemainder is:");
for(i=1;i<=n;i++)
printf("%d",r[i]);
printf("\n\nTransmitted Frame is:");
for(i=m+1,j=1;i<=m+n;i++,j++)
a[i]=r[j];
for(i=0;i<=m+n;i++)
printf("%d",a[i]);
printf("\n");
printf("\nEnter the Degree of Frame to be Sent:");
scanf("%d",&m);
printf("\n\nEnter the Frame:");
for(i=0;i<=m;i++)
scanf("%d",&a[i]);
for(j=0;j<=n;j++)
r[j]=a[j];
k=0;
for(i=n;i<=m;i++)
{
if(i>n)
{
for(j=0;j<n;j++)
r[j]=r[j+1];
r[j]=a[i];
}
if(r[0])
div[k++]=1;
else
{
div[k++]=0;
continue;
}
for(j=0;j<=n;j++)
r[j]=r[j]^g[j];
}
printf("\nQuotient is:");
for(j=0;j<k;j++)
printf("%d",div[j]);
printf("\n\nRemainder is:");
for(i=1;i<=n;i++)
printf("%d",r[i]);
for(i=1;i<=n;i++)
{
if(r[i])
flag=0;
}
if(flag)
printf("\n\nNo error in the Transmission\n\n");
else
printf("\n\nError in the Transmission\n\n");
return 0;
}
OUTPUT:
RESULT:
Thus, the error detection and error correction (CRC) is
implemented successfully.
AIM:
To implement error detection and error correction
techniques (hamming code) using C language.
SOFTWARE REQUIRED:
• Linux OS – Ubuntu
• C Compiler - gcc
THEROY:
Hamming code is a technique used in error detection and
correction in digital data transmission and storage systems. It was
developed by Richard Hamming in the 1950s and is named after him.
The purpose of hamming code is to add redundancy to the
transmitted data, allowing the receiver to detect and correct single-
bit errors that may occur during transmission.
ALGORITHM:
• Determine the number of parity bits required (r) based on the
length of the data (m).
• Calculate the smallest number r such that m + r + 1 <=
2^r.
• The total number of bits in the encoded data will be m + r.
• Create an array to store the encoded data with a size of m+r.
PROGRAM:
#include <stdio.h>
#include <stdbool.h>
// Function to calculate the number of parity bits required
int calculateParityBits(int dataSize) {
int r = 0;
while ((1 << r) < dataSize + r + 1)
r++;
return r;
}
// Function to calculate the parity bits
void calculateParity(int* encodedData, int dataSize, int*
parityIndices) {
int r = calculateParityBits(dataSize);
if (errorIndex != 0) {
printf("Error detected at bit %d\n", errorIndex);
receivedData[errorIndex - 1] ^= 1; // Flip the error bit
printf("Corrected Data: ");
} else {
printf("No errors detected\nCorrected Data: ");
}
for (int i = 0; i < dataSize; i++) {
printf("%d ", receivedData[i]);
}
printf("\n");
}
int main() {
int dataSize;
printf("Enter the size of the data: ");
scanf("%d", &dataSize);
int data[dataSize];
printf("Enter the data (0s and 1s): ");
for (int i = 0; i < dataSize; i++) {
scanf("%d", &data[i]);
}
int r = calculateParityBits(dataSize);
return 0;
}
OUTPUT:
RESULT:
Thus, the error detection and error correction (hamming
code) is implemented successfully.
AIM:
SOFTWARE REQUIRED:
• Linux OS – Ubuntu
• C Compiler - gcc
THEORY:
Else:
• Resend the packet.
• Go back to step 5.
Receiver Algorithm:
8. Wait for a packet from the sender.
9. If the received packet has the expected sequence number:
• Extract the data from the packet.
• Send an ACK with the sequence number back to the
sender.
• Deliver the data to the application layer.
10. If the received packet has an unexpected sequence number:
• Discard the packet.
• Send an ACK with the previous sequence number back
to the sender (duplicate ACK).
11. Go back to step 8.
PROGRAM:
a) Stop and wait protocol – Sender
#include<stdio.h>
#include<time.h>
#define TIMEOUT 1
int main()
{
int frames[10],n,i,j;
printf("Enter the number of frames: ");
scanf("%d",&n);
printf("Enter the frames: ");
for(i=0;i<n;i++)
scanf("%d",&frames[i]);
printf("\nSending Frames...\n");
for(i=0;i<n;i++)
{
printf("\nSending Frame %d",i+1);
//simulate transmission delay
sleep(5);
//wait for acknowledgement
time_t start=time(NULL);
while(time(NULL)-start<TIMEOUT)
{
if(feof(stdin)) //end of input reached
break;
int ack;
if(scanf("%d",&ack)==1) //acknowledgement received
{
if(ack==i+1)
{
printf("\nAcknowledgement received for Frame %d",i+1);
break;
}
else //incorrect acknowledgement received
printf("\nIncorrect acknowledgement received for Frame
%d",i+1);
}
}
//if acknowledgement not received within timeout period
if(time(NULL)-start>=TIMEOUT)
{
printf("\nAcknowledgement not received for Frame %d",i+1);
printf("\nResending Frame %d",i+1);
i--;
}
}
printf("\nAll frames sent successfully!");
return 0;
}
OUTPUT:
Fig: 3a.1 Stop and Wait Protocol -Sender
Fig no: 3a.2 Stop and Wait Protocol-Receiver
RESULT:
Thus, the stop and wait protocol is implemented successfully.
AIM:
SOFTWARE REQUIRED:
• Linux OS – Ubuntu
• C Compiler - gcc
THEORY:
The sliding window protocol is a communication protocol
used in computer networks to ensure reliable and efficient data
transmission between a sender and a receiver. It allows multiple
packets to be sent without waiting for an acknowledgment for each
individual packet.
ALGORITHM:
Sender Side:
PROGRAM:
#include<stdio.h>
int main(){
int w,i,f,frames[50];
printf("Enter window size: ");
scanf("%d",&w);
printf("\nEnter number of frames to transmit: ");
scanf("%d",&f);
printf("\nEnter %d frames: ",f);
for(i=1;i<=f;i++)
scanf("%d",&frames[i]);
printf("\nWith sliding window protocol the frames will be sent in
the following manner (assuming no corruption of frames)\n\n");
printf("After sending %d frames at each stage sender waits for
acknowledgement sent by the receiver\n\n",w);
for(i=1;i<=f;i++){
if(i%w==0) {
printf("%d\n",frames[i]);
printf("Acknowledgement of above frames sent is received by
sender\n\n");
}
else
printf("%d ",frames[i]);
}
if(f%w!=0)
printf("\nAcknowledgement of above frames sent is received by
sender\n");
return 0;
}
OUTPUT:
Fig no: 3b.1 SLIDING WINDOW PROTOCOL
RESULT:
Thus, the sliding window protocol is implemented successfully.
Aim:
To implement the Go back-N Protocols using C program.
SOFTWARE REQUIRED:
• Linux OS – Ubuntu
• C Compiler - gcc
THEORY:
The Go Back-N ARQ or Go Back Automatic Repeat Request
is a way to implement sliding window protocol. This protocol is used
for flow control in networking and is a part of the data-link layer. The
sender’s window is of size N and the receiver’s window size is
always one.The window sizes for Go Back-N.
1. Sender Window Size (WS)
The WS is equal to N. If we say the protocol is GB-4, then WS
= 4. In order to implement pipelining, the window size should always
be greater than one. If window size is one, the protocol reduces to
stop-and -wait protocol.
2. Receiver Window Size (WR)
WR is always one in Go Back-N. Now we will understand how
Go Back-N actually works with the help of an example. In the
diagram below the sender’s window has a size of four, or Go Back-
4. Assume that we’ve plenty of sequence numbers, for the sake of
explanation. Now the sender has despatched the packets zero, one,
two and three. After acknowledging the packets zero and one.
ALGORITHM:
• Open linux software and type the program for Go back-N
protocol.
• The size of the sender window in Go-Back-N ARQ is N.
• The size of the receiver window is 1.
• When the acknowledgement for one frame is not received by
the sender, the entire window is retransmitted, starting with the
corrupted frame.
• GO Back – N provides for sending multiple frames before
receiving the acknowledgment for the first frame.
• The frames are sequentially numbered and a finite number of
frames. The maximum number of frames that can be sent
depends upon the size of the sending window.
• If the acknowledgment of a frame is not received within an
agreed upon time period, all frames starting from that frame
are retransmitted.
• The size of the sending window determines the sequence
number of the outbound frames. If the sequence number of the
frames is an n-bit field, then the range of sequence numbers
n
that can be assigned is 0 to 2 −1.
n
• Consequently, the size of the sending window is 2 −1. Thus in
n
order to accommodate a sending window size of 2 −1, a n-bit
sequence number is chosen.
• The sequence numbers are numbered as modulo-n. For
example, if the sending window size is 4, then the sequence
numbers will be 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, and so on. The
number of bits in the sequence number is 2 to generate the
binary sequence 00, 01, 10, 11.
• Run the program.
PROGRAM:
a)GO BACK-N PROTOCOL – SENDER
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#include<time.h>
#include<stdlib.h>
#include<ctype.h>
#include<arpa/inet.h>
#define W 5
#define P1 50
#define P2 10
char a[10];
char b[10];
void alpha9(int);
int main(){
struct sockaddr_in ser,cli;
int s,n,sock,i,j,c=1,f;
unsigned int s1;
s=socket(AF_INET,SOCK_STREAM,0);
ser.sin_family=AF_INET;
ser.sin_port=6500;
ser.sin_addr.s_addr=inet_addr("127.0.0.1");
bind(s,(struct sockaddr *) &ser, sizeof(ser));
listen(s,1);
n=sizeof(cli);
sock=accept(s,(struct sockaddr *)&cli, &n);
printf("\nTCP Connection Established.\n");
s1=(unsigned int) time(NULL);
srand(s1);
strcpy(b,"Time Out ");
recv(sock,a,sizeof(a),0);
f=atoi(a);
while(1){
for(i=0;i<W;i++){
recv(sock,a,sizeof(a),0);
if(strcmp(a,b)==0){
break;
}
}
i=0;
while(i<W)
{
j=rand()%P1;
if(j<P2){
send(sock,b,sizeof(b),0);
break;
}else{
alpha9(c);
if(c<=f){
printf("\nFrame %s Received ",a);
send(sock,a,sizeof(a),0);
}else{
break;
}
c++;
}
i++;
f(c>f){
break;
}
i++;
}
}
close(sock);
close(s);
return 0;
}
void alpha9(int z){
int k,i=0,j,g;
k=z;
while(k>0){
i++;
k=k/10;
}
g=i;
i--;
while(z>0){
k=z%10;
a[i]=k+48;
i--;
z=z/10;
}
a[g]='\0';
}
OUTPUT:
Fig no: 4a.1 GO BACK-N PROTOCOL – SENDER
RESULT :
Thus, the GO Back-N protocol using c program has been
implemented.
AIM:
To implement the distance vector routing algorithm using C
program.
SOFTWARE REQUIRED:
• Linux OS – Ubuntu
• C Compiler - gcc
THEORY:
A distance-vector routing protocol is one of the foremost
instructions of routing protocols in pc conversation principle for
packet-switched networks. The hyperlink-nation protocol is the
alternative foremost class. The Bellman-Ford set of rules is applied
in a distance-vector routing protocol to calculate paths.
A distance-vector routing protocol calls for that a router notify
its buddies on every occasion a community's topology adjustments
or, in a few cases, on every occasion a alternate is detected. Distance-
vector routing protocols have much less message overhead and
computational complexity than hyperlink-nation protocols, which
require a router to inform all community nodes of adjustments to the
topology.
ALGORITHM:
• This algorithm requires each node in the network to maintain
a distance vector table that stores the distance between itself
and its immediate neighbours in the link.
• This algorithm can then be used to draw the following
conclusions about the network's routing algorithm.
• Routing table is used to share distance vectors between
adjacent nodes.
• The latest network distance vector values are shared by each
routing table.
• The distance vector over the nearest node is updated each time
data from the routing table is shared across the network.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX_NODES 10
#define INFINITY 99999
// Structure to represent a node in the network
struct Node {
int cost[MAX_NODES];
int via[MAX_NODES];
};
// Function to initialize the routing table for a node
void initialize(struct Node* node, int numNodes, int self) {
int i;
for (i = 0; i < numNodes; i++) {
node->cost[i] = INFINITY;
node->via[i] = -1;
}
node->cost[self] = 0;
node->via[self] = self;
}
// Function to perform distance vector routing using Bellman-Ford
algorithm
void distanceVectorRouting(struct Node* nodes, int numNodes) {
int i, j, k;
int updated;
for (i = 0; i < numNodes; i++) {
for (j = 0; j < numNodes; j++) {
for (k = 0; k < numNodes; k++) {
if (nodes[j].cost[i] + nodes[i].cost[k] < nodes[j].cost[k]) {
nodes[j].cost[k] = nodes[j].cost[i] + nodes[i].cost[k];
nodes[j].via[k] = i;
}
}
}
}
// Check for any changes in the routing tables
updated = 0;
for (i = 0; i < numNodes; i++) {
for (j = 0; j < numNodes; j++) {
for (k = 0; k < numNodes; k++) {
if (nodes[j].cost[i] + nodes[i].cost[k] < nodes[j].cost[k]) {
nodes[j].cost[k] = nodes[j].cost[i] + nodes[i].cost[k];
nodes[j].via[k] = i;
updated = 1;
}
}
}
}
if (updated) {
// Recompute routing tables if changes occurred
distanceVectorRouting(nodes, numNodes);
}
}
// Function to display the routing tables for all nodes
void displayRoutingTables(struct Node* nodes, int numNodes)
{
int i, j;
printf("\nRouting Tables:\n");
for (i = 0; i < numNodes; i++) {
printf("\nRouting Table for Node %d:\n", i);
printf("Destination\tNext Hop\tCost\n");
for (j = 0; j < numNodes; j++)
{
printf("%d\t\t%d\t\t%d\n", j, nodes[i].via[j], nodes[i].cost[j]);
}
}
printf("\n");
}
int main() {
int numNodes, i, j;
struct Node nodes[MAX_NODES];
printf("Enter the number of nodes (maximum %d): ",
MAX_NODES);
scanf("%d", &numNodes);
// Initialize the nodes
for (i = 0; i < numNodes; i++)
{
initialize(&nodes[i], numNodes, i);
}
// Input the link cost
printf("\nEnter the link costs (0 for self, -1 for no link):\n");
for (i = 0; i < numNodes; i++)
{
for (j = 0; j < numNodes; j++)
{
if (i != j)
{
printf("Link cost from Node %d to Node %d: ", i, j);
scanf("%d", &nodes[i].cost[j]);
}
}
}
// Perform distance vector routing
distanceVectorRouting(nodes, numNodes);
// Display the routing tables
displayRoutingTables(nodes, numNodes);
return 0;
}
OUTPUT:
Fig no: 5.1 DISTANCE VECTOR ROUTING ALGORITHM
RESULT :
Thus, the distance vector routing algorithm is implemented
successfully.
AIM:
To implementation of link state routing algorithm (open shortest
path first) with 5 nodes (Dijkstra’s) using C language.
SOFTWARE REQUIRED:
• Linux OS – Ubuntu
• C Compiler - gcc
THEROY:
ALGORITHM:
• Set the source node as the current node and mark it as visited.
• Select the neighbor with the minimum cost from the priority
queue as the next current node.
• Repeat steps 6-7 until all nodes have been visited or until the
priority queue is empty.
• After visiting all nodes, the routing table for each node will
contain the shortest path information to reach all other nodes
in the network.
PROGRAM:
#include <stdio.h>
#include <stdbool.h>
#define INF 9999
#define NUM_NODES 5
void dijkstra(int graph[NUM_NODES][NUM_NODES], int source) {
int distance[NUM_NODES];
bool visited[NUM_NODES];
for (int i = 0; i < NUM_NODES; i++) {
distance[i] = INF;
visited[i] = false;
} distance[source] = 0;
for (int count = 0; count < NUM_NODES - 1; count++) {
int minDistance = INF;
int minIndex = -1;
for (int v = 0; v < NUM_NODES; v++) {
if (!visited[v] && distance[v] <= minDistance) {
minDistance = distance[v];
minIndex = v;
}
}visited[minIndex] = true;
for (int v = 0; v < NUM_NODES; v++) {
if (!visited[v] && graph[minIndex][v] != INF &&
distance[minIndex] != INF && distance[minIndex] +
graph[minIndex][v] < distance[v]) {
distance[v] = distance[minIndex] + graph[minIndex][v];
}
}
}printf("Node\tDistance from Source\n");
for (int i = 0; i < NUM_NODES; i++) {
printf("%c\t%d\n", 'A' + i, distance[i]);}
}
int main() {
int graph[NUM_NODES][NUM_NODES] = {
OUTPUT:
Fig no: 6.1 LINK STATE ROUTING ALGORITHM
RESULT:
Thus, the link state routing algorithm with 5 nodes is implemented
successfull
AIM:
To implement Encryption & Decryption using Data
Encryption Standard algorithm.
SOFTWARE REQUIRED:
• Linux OS – Ubuntu
• C Compiler - gcc
THEORY:
The Data Encryption Standard (DES) is a symmetric
encryption algorithm that was widely used for secure
communication and data protection. However, it is now considered
outdated and insecure for modern cryptographic purposes due to
its
ALGORITHM:
Encryption:
Decryption:
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
/*
* des.h provides the following functions and constants:
*
* generate_key, generate_sub_keys, process_message,
ENCRYPTION_MODE, DECRYPTION_MODE
*
*/
#include "des.h"
// Declare file handlers
static FILE *key_file, *input_file, *output_file;
// Declare action parameters
#define ACTION_GENERATE_KEY "-g"
#define ACTION_ENCRYPT "-e"
#define ACTION_DECRYPT "-d"
// DES key is 8 bytes long
#define DES_KEY_SIZE 8
int main(int argc, char* argv[]) {
clock_t start, finish;
double time_taken;
unsigned long file_size;
unsigned short int padding;
if (argc < 2) {
printf("You must provide at least 1 parameter, where you specify
the action.");
return 1;
}
if (strcmp(argv[1], ACTION_GENERATE_KEY) == 0) {
// Generate key file
if (argc != 3) {
printf("Invalid # of parameter specified. Usage: run_des -g
keyfile.key");
return 1;
}
key_file = fopen(argv[2], "wb");
if (!key_file) {
printf("Could not open file to write key.");
return 1;
}
unsigned int iseed = (unsigned int)time(NULL);
srand (iseed);
short int bytes_written;
unsigned char* des_key = (unsigned char*) malloc(8*sizeof(char));
generate_key(des_key);
bytes_written = fwrite(des_key, 1, DES_KEY_SIZE, key_file);
if (bytes_written != DES_KEY_SIZE) {
printf("Error writing key to output file.");
fclose(key_file);
free(des_key);
return 1;
}
free(des_key);
fclose(key_file);
} else if ((strcmp(argv[1], ACTION_ENCRYPT) == 0) ||
(strcmp(argv[1], ACTION_DECRYPT) == 0)) { // Encrypt or decrypt
if (argc != 5) {
printf("Invalid # of parameters (%d) specified. Usage: run_des [-e|-
d] keyfile.key input.file output.file", argc);
return 1;
}
// Read key file
key_file = fopen(argv[2], "rb");
if (!key_file) {
printf("Could not open key file to read key.");
return 1;
}
short int bytes_read;
unsigned char* des_key = (unsigned char*) malloc(8*sizeof(char));
bytes_read = fread(des_key, sizeof(unsigned char), DES_KEY_SIZE,
key_file);
if (bytes_read != DES_KEY_SIZE) {
printf("Key read from key file does nto have valid key size.");
fclose(key_file);
return 1;
}
fclose(key_file);
// Open input file
input_file = fopen(argv[3], "rb");
if (!input_file) {
printf("Could not open input file to read data.");
return 1;
}
// Open output file
output_file = fopen(argv[4], "wb");
if (!output_file) {
printf("Could not open output file to write data.");
return 1;
}
// Generate DES key set
short int bytes_written, process_mode;
unsigned long block_count = 0, number_of_blocks;
unsigned char* data_block = (unsigned char*)
malloc(8*sizeof(char));
unsigned char* processed_block = (unsigned char*)
malloc(8*sizeof(char));
key_set* key_sets = (key_set*)malloc(17*sizeof(key_set));
start = clock();
generate_sub_keys(des_key, key_sets);
finish = clock();
time_taken = (double)(finish - start)/(double)CLOCKS_PER_SEC;
// Determine process mode
if (strcmp(argv[1], ACTION_ENCRYPT) == 0) {
process_mode = ENCRYPTION_MODE;
printf("Encrypting..\n");
} else {
process_mode = DECRYPTION_MODE;
printf("Decrypting..\n");
}
// Get number of blocks in the file
fseek(input_file, 0L, SEEK_END);
file_size = ftell(input_file);
fseek(input_file, 0L, SEEK_SET);
number_of_blocks = file_size/8 + ((file_size%8)?1:0);
start = clock();
// Start reading input file, process and write to output file
while(fread(data_block, 1, 8, input_file)) {
block_count++;
if (block_count == number_of_blocks) {
if (process_mode == ENCRYPTION_MODE) {
padding = 8 - file_size%8;
f (padding < 8) { // Fill empty data block bytes with padding
memset((data_block + 8 - padding), (unsigned char)padding,
padding);
}
process_message(data_block, processed_block, key_sets,
process_mode);
bytes_written = fwrite(processed_block, 1, 8, output_file);
if (padding == 8) {
// Write an extra block for padding
memset(data_block, (unsigned char)padding, 8);
process_message(data_block, processed_block, key_sets,
process_mode);
bytes_written = fwrite(processed_block, 1, 8, output_file);
}
} else {
process_message(data_block, processed_block, key_sets,
process_mode);
padding = processed_block[7];
if (padding < 8) {
bytes_written = fwrite(processed_block, 1, 8 - padding,
output_file);
}
}
} else {
process_message(data_block, processed_block, key_sets,
process_mode);
bytes_written = fwrite(processed_block, 1, 8, output_file);
}
memset(data_block, 0, 8);
}
finish = clock();
// Free up memory
free(des_key);
free(data_block);
free(processed_block);
fclose(input_file);
fclose(output_file);
// Provide feedback
time_taken = (double)(finish - start)/(double)CLOCKS_PER_SEC;
printf("Finished processing %s. Time taken: %lf seconds.\n",
argv[3], time_taken);
return 0;
} else {
printf("Invalid action: %s. First parameter must be [ -g | -e | -d ].",
argv[1]);
return 1;
}
return 0;
}
OUTPUT:
RESULT:
Thus, the Encryption and Decryption algorithm has been
implemented successfully.
AIM:
To implement data encryption and decryption using
RSA(Rivest,Shamir and Adleman) algorithm.
SOFTWARE REQUIRED:
• Linux OS – Ubuntu
• C Compiler - gcc
THEORY:
RSA algorithm is an asymmetric cryptography algorithm.
Asymmetric actually means that it works on two different keys
i.e.Public Key and Private Key.As the name describes that the Public
Key is given to everyone and the Private key is kept private.
The public key consists of two numbers where one number is a
multiplication of two large prime numbers. And private key is also
derived from the same two prime numbers. So if somebody can
factorize the large number, the private key is compromised.
Therefore encryption strength totally lies on the key size and if we
double or triple the key size, the strength of encryption increases
exponentially. RSA keys can be typically 1024 or 2048 bits long, but
experts believe that 1024-bit keys could be broken in the near
future. But till now it seems to be an infeasible task.
ALGORITHM:
• M denotes the original message it is first passed into a hash
function denoted by H# to scramble the data before
transmission.
• It then bundled the message together with the hash digest,
denoted by h, and encrypts it using the sender’s private key.
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
// Function to calculate (base^exponent) % modulus
long long int power(long long int base, long long int exponent, long
long int modulus)
{
long long int result = 1;
while (exponent > 0)
{
if (exponent % 2 == 1)
result = (result * base) % modulus;
base = (base * base) % modulus;
exponent = exponent / 2;
}
return result;
}
while (plaintext[i])
{
encrypted[i] = power(plaintext[i], e, n);
i++;
}
encrypted[i] = -1; // Mark the end of the array
printf("Encrypted message: ");
for (int j = 0; encrypted[j] != -1; j++)
{
printf("%lld ", encrypted[j]);
}
printf("\n");
}
decrypted[i] = '\0';
printf("Decrypted message: %s\n", decrypted);
}
int main()
{
long long int p, q, n, phi, e, d;
char plaintext[100];
long long int encrypted[100]; // Declare encrypted array
OUTPUT:
Fig no: 8.1 RSA ALGORITHMS
RESULT:
Thus, the data encryption and decryption using RSA
algorithm is implemented.
AIM:
To implement the program of client server model using (File
Transfer Protocol) FTP in C program.
SOFTWARE REQUIRED:
• Linux OS – Ubuntu
• C Compiler – gcc
THEORY:
FTP (File Transfer Protocol) is a network protocol for
transmitting files between computers over Transmission Control
Protocol/Internet Protocol (TCP/IP) connections. Within the TCP/IP
suite, FTP is considered an application layer protocol.
In an FTP transaction, the end user's computer is typically
called the local host. The second computer involved in FTP is a
remote host, which is usually a server. Both computers need to be
connected via a network and configured properly to transfer files via
FTP. Servers must be set up to run FTP services, and the client must
have FTP software installed to access these services.
Although many file transfers can be conducted using
Hypertext Transfer Protocol (HTTP) -- another protocol in the
TCP/IP suite -- FTP is still commonly used to transfer files behind
the scenes for other applications, such as banking services. It is also
sometimes used to download new applications via web browsers.
ALGORITHM:
A) SERVER:
1. Start
2. Declare the variables for the socket
3. Specify the family, protocol, IP address and port number
4. Create a socket using socket() function
5. Bind the IP address and Port number
6. Listen and accept the client’s request for the connection
7. Establish the connection with the client
8. Close the socket
9. Stop
B) CLIENT:
1. Start
2. Declare the variables for the socket
3. Specify the family, protocol, IP address and port number
4. Create a socket using socket() function
5. Call the connect() function
6. Close the socket
7. Stop
PROGRAM:
A) SERVER:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define MAXSIZE 1024
void receiveFile(int sockfd, char *fileName)
{
int n;
FILE *fp;
char buffer[MAXSIZE];
fp = fopen(fileName, "w");
while ((n = recv(sockfd, buffer, MAXSIZE, 0)) > 0)
{
fwrite(buffer, sizeof(char), n, fp);
}
printf("File received successfully.\n");
fclose(fp);
}
void sendFile(int sockfd, char *fileName)
{ int n;
FILE *fp;
char buffer[MAXSIZE];
fp = fopen(fileName, "r");
if (fp == NULL)
{
printf("File not found.\n");
return;
}
while (fgets(buffer, MAXSIZE, fp) != NULL)
{
if (send(sockfd, buffer, sizeof(buffer), 0) == -1)
{
printf("Error in sending file.\n");
return;
}
bzero(buffer, MAXSIZE);
}
fclose(fp);
printf("File sent successfully.\n");
}
int main()
{
int sockfd, n;
char buffer[MAXSIZE];
struct sockaddr_in serverAddress;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
{
printf("Error in creating socket.\n");
return 1;
}
bzero(&serverAddress, sizeof(serverAddress));
serverAddress.sin_family = AF_INET;
serverAddress.sin_port = htons(4444);
serverAddress.sin_addr.s_addr = inet_addr("127.0.0.1");
if (connect(sockfd, (struct sockaddr *)&serverAddress,
sizeof(serverAddress)) < 0)
{
printf("Error in connecting to server.\n");
return 1;
}
printf("Connected to server.\n");
while (1)
{
printf("Enter command: ");
bzero(buffer, MAXSIZE);
fgets(buffer, MAXSIZE, stdin);
if (send(sockfd, buffer, sizeof(buffer), 0) == -1)
{
printf("Error in sending command.\n");
return 1;
}
if (strncmp("get", buffer, 3) == 0)
{
char fileName[MAXSIZE];
sscanf(buffer, "%*s %s", fileName);
receiveFile(sockfd, fileName);
}
else if (strncmp("put", buffer, 3) == 0)
{
char fileName[MAXSIZE];
sscanf(buffer, "%*s %s", fileName);
sendFile(sockfd, fileName);
}
else if (strncmp("ls", buffer, 2) == 0)
{
while ((n = recv(sockfd, buffer, MAXSIZE, 0)) > 0)
{
printf("%s", buffer);
}
}
else if (strncmp("quit", buffer, 4) == 0)
{
break;
}else{
printf("Invalid command.\n");
}}
close(sockfd);
printf("Disconnected from server.\n");
return 0;
}
B) CLIENT
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <fcntl.h>
#include <sys/stat.h>
#define PORT 4444
int main() {
int sockfd, new_sockfd, ret;
struct sockaddr_in serverAddr, newAddr;
char buffer[1024];
pid_t childpid;
char *filename;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if(sockfd < 0) {
printf("Error in connection.\n");
exit(1);
}
printf("Server Socket is created.\n");
memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PORT);
serverAddr.sin_addr.s_addr = INADDR_ANY;
ret = bind(sockfd, (struct sockaddr*)&serverAddr,
sizeof(serverAddr));
if(ret < 0) {
printf("Error in binding.\n");
exit(1);
}
printf("Bind to port %d\n", 4444);
if(listen(sockfd, 10) == 0){
printf("Listening....\n");
}else{
printf("Error in binding.\n");
}
while(1) {
new_sockfd = accept(sockfd, (struct sockaddr*)&newAddr,
sizeof(newAddr));
if(new_sockfd < 0) {
exit(1);}
printf("Connection accepted from %s:%d\n",
inet_ntoa(newAddr.sin_addr), ntohs(newAddr.sin_port));
if((childpid = fork()) == 0) {
close(sockfd);
while(1) {
recv(new_sockfd, buffer, 1024, 0);
if(strcmp(buffer, "quit") == 0) {
printf("Disconnected from %s:%d\n",
inet_ntoa(newAddr.sin_addr), ntohs(newAddr.sin_port));
break;
}
else if(strcmp(buffer, "list") == 0) {
system("ls > /tmp/file_list.txt");
filename = "/tmp/file_list.txt";
int fd = open(filename, O_RDONLY);
struct stat file_stat;
fstat(fd, &file_stat);
int size = file_stat.st_size;
send(new_sockfd, &size, sizeof(int), 0);
sendfile(new_sockfd, fd, NULL, size);
}
else {
filename = buffer;
FILE *fp = fopen(filename, "r");
if (fp == NULL) {
printf("File not found.\n");
char *error_message = "File not found.";
send(new_sockfd, error_message, strlen(error_message), 0);
}
else {
fseek(fp, 0, SEEK_END);
int size = ftell(fp);
rewind(fp);
send(new_sockfd, &size, sizeof(int), 0);
char *buffer = malloc(size);
fread(buffer, 1, size, fp);
send(new_sockfd, buffer, size, 0);
fclose(fp);
}
}
}
}
}
close(new_sockfd);
return 0;
}
OUTPUT:
Fig no: 9.1SERVER MODEL USING FTP
Fig no: 9.2 CLIENT MODEL USING FTP
RESULT:
Thus the FTP client server protocol using c has been implemented.
AIM:
To Implement and realize the start topology networks using
NS 2.
SOFTWARE REQUIRED:
• NS-2 Simulator
THEORY:
Star networks are one of the most common computer
network topologies. In its simplest form, a star network consists
of one central switch, hub or computer, which acts as a conduit
to transmit messages. In star topology, every node (computer
workstation orany other peripheral) is connected to a central
node called a hub or switch. Theswitch is the server and the
peripherals are the clients. Thus, the hub and leaf nodes,and
the transmission lines between them, form a graph with the
topology of a star.
ALGORITHM:
• Create a simulator object
• Define different colors for different data flows.
• Open a nam trace file and define finish procedure then
close the tracefile, and execute
• nam on trace file.
•
• Create six nodes that forms a network numbered from 0
to 5•
• Create duplex links between the nodes to form a STAR
Topology
• Setup TCP Connection between n(1) and n(3)
• Apply CBR Traffic over TCP.
• Schedule events and run the program .
PROGRAM:
#Star Topology
set ns [new Simulator]
set nf [open out.nam w]
$ns namtrace-all $nf
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$n0 shape circle
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
$ns duplex-link $n0 $n2 1Mb 10ms DropTail
$ns duplex-link $n0 $n3 1Mb 10ms DropTail
$ns duplex-link $n0 $n4 1Mb 10ms DropTail
$ns duplex-link $n0 $n5 1Mb 10ms DropTail
set tcp0 [new Agent/TCP]
$tcp0 set class_ 1
$ns attach-agent $n1 $tcp0
set sink0 [new Agent/TCPSink]
$ns attach-agent $n3 $sink0
$ns connect $tcp0 $sink0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.01
$cbr0 attach-agent $tcp0
$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"
$ns at 5.0 "finish"
$ns run
OUTPUT:
Fig no: 10a.1 Network Topology – Star using NS 2
RESULT:
Thus, the star network topology using NS 2 is verified
AIM:
To Implement and realize the bus topology networks using
NS 2
SOFTWARE REQUIREMENTS:
• NS-2 Simulator
THEORY:
Token bus is a LAN protocol operating in the MAC layer. Token
bus is standardized as per IEEE802.4. Token bus can operate at
speeds of 5Mbps, 10Mbps and 20 Mbps. The operation of token bus
is as follows: Unlike token ring in token bus the ring topology is
virtually created and maintained by the protocol. Anode can receive
data even if it is not part of the virtual ring, a node joins the virtual
ring only if it has data to transmit. In token bus data is transmitted
to the destination node only where as other control frames is hop
to hop.
ALGORITHM:
• Create a simulator object
• Define different colours for different data flows
• Open a nam trace file and define finish procedure then close
the trace file,
• And execute nam on trace file.
• Create five nodes that forms a network numbered from 0 to
4
• Create duplex inks between the nodes and add Orientation to
the nodes
• for setting a LAN topology
• Setup TCP Connection between n(1) and n(3)
• Apply CBR Traffic over TCP.
• Schedule events and run the program.
PROGRAM:
#Bus Topology
set ns [new Simulator]
set nf [open out.nam w]
$ns namtrace-all $nf
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set lan0 [$ns newLan "$n0 $n1 $n2 $n3 $n4 $n5" 0.5Mb 10ms LL
Queue/DropTail MAC/Csma/Cd channel]
set tcp0 [new Agent/TCP]
$tcp0 set class_ 1
$ns attach-agent $n1 $tcp0
set sink0 [new Agent/TCPSink]
$ns attach-agent $n3 $sink0
$ns connect $tcp0 $sink0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 5
$cbr0 set interval_ 0.01
$cbr0 attach-agent $tcp0
$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"
$ns at 5.0 "finish"
$ns run
OUTPUT:
SOFTWARE REQUIREMENTS:
• NS-2 Simulator
THEORY:
Token ring is a LAN protocol operating in the MAC layer.
Token ring is standardized as per IEEE802.5. Token ring can operate
at speeds of 4mbpsand 16 Mbps.
The operation of token ring is as follows: When there is no
traffic on the network a simple 3-byte token circulates the ring. If
the token is free (no reserved by a station of higher priority as
explained later) then the station may seize the token and start
sending the data frame.
ALGORITHM:
• Create a simulator object
• Define different colors for different data flows
• Open a nam trace file and define finish procedure then close
the trace file,
• and execute Nam on trace file.
• Create five nodes that forms a network numbered from 0 to
4
• Create duplex links between the nodes to form a Ring
Topology.
• Setup TCP Connection between n(1) and n(3)
• Apply CBR Traffic over TCP.
• Schedule events and run the program.
PROGRAM:
#Star Topology
set ns [new Simulator]
set nf [open out.nam w]
$ns namtrace-all $nf
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail
$ns duplex-link $n3 $n4 1Mb 10ms DropTail
$ns duplex-link $n4 $n5 1Mb 10ms DropTail
$ns duplex-link $n5 $n0 1Mb 10ms DropTail
set tcp0 [new Agent/TCP]
$tcp0 set class_ 1
$ns attach-agent $n1 $tcp0
set sink0 [new Agent/TCPSink]
$ns attach-agent $n3 $sink0
$ns connect $tcp0 $sink0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.01
$cbr0 attach-agent $tcp0
$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"
$ns at 5.0 "finish"
$ns run
OUTPUT:
Fig no: 10c.1 Network Topology – Ring using NS 2
RESULT:
Thus, the bus network topology using NS 2 is implemented.
AIM:
To implement and realize the mesh topology network using
NS2.
SOFTWARE REQURIED:
• NS-2 Simulator
THEORY:
Mesh topology is a network design where each device is
connected to every other device in a point-to-point manner. In a
mesh network, devices are interconnected with multiple direct
links, creating a redundant and robust network structure.
Mesh networks are commonly used in situations where
reliability and fault tolerance are critical, such as in
telecommunications networks, large-scale data centers, or military
and aerospace applications.6
ALGORITHM:
• Create a simulator object.
• Define different colors for different data flows.
• Open a nam trace file and define finish procedure then
close the
Trace file, and execute Nam on trace file.
• Create five nodes that forms a network numbered
from 0 to 4.
• Create duplex links between the nodes to form a Mesh
Topology.
• Setup TCP Connection between n(1) and n(3).
• Apply CBR Traffic over TCP.
• Run the program.
PROGRAM:
#MESH TOPOLOGY
#create a Simulator object
set ns [new Simulator]
#Open the nam trace file
set nf [open out.nam w]
$ns namtrace-all $nf
#Define a "finish" procedure
proc finish {} {
global ns nf
$ns flush-trace
#close the trace file
close $nf
#Executenam on the trace file
exec nam out.nam &
exit 0
}
#create four nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
#create links between the nodes
$ns duplex-link $n0 $n1 1Mb 10ms DropTail
$ns duplex-link $n0 $n2 1Mb 10ms DropTail
$ns duplex-link $n0 $n3 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n1 $n3 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail
#create a TCP agent and attach it to node n0
set tcp0 [new Agent/TCP]
$tcp0 set class_ 1
$ns attach-agent $n1 $tcp0
#create a TCP sink agent
set sink0 [new Agent/TCPSink]
$ns attach-agent $n3 $sink0
#connect the traffic sources with the traffic sink
$ns connect $tcp0 $sink0
#create a CBR traffic source and attach it to tcp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.01
$cbr0 attach-agent $tcp0
#schedule events
$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"
$ns at 5.0 "finish"
$ns run
OUTPUT:
Fig no: 10d.4 Network Topology – Mesh
RESULT:
Thus, the Mesh Topology network using NS 2 is implemented.
AIM:
To create scenario and study the performance of CSMA/ CA
and CSMA/ CD protocol using NS2.
SOFTWARE REQUIREMENTS:
• NS-2 Simulator
THEORY:
Ethernet is a LAN (Local area Network) protocol operating at
the MAC (Medium Access Control) layer. Ethernet has been
standardized as per IEEE802.3. The underlying protocol in Ethernet
is known as the CSMA/ CD–Carrier Sense Multiple Access/ Collision
Detection. The working of the Ethernet protocol is as explained
below, A node which has data to transmit senses the channel. If the
channel is idle then, the data is transmitted.
ALGORITHM:
• Create a simulator object.
• Define different colors for different data flows.
• Open a nam trace file and define finish procedure then close
the trace file,
• and execute nam
• On trace file.
• Create six nodes that forms a network numbered from 0 to
5.
• Create duplex links between the node sand add Orientation
to the nodes
• For setting a LAN Topology.
• Setup TCP Connection between n(0) and n(4).
• Apply FTP Traffic over TCP.•
• Setup UDP Connection between n(1) and n(5).
• Apply CBR Traffic over UDP.
• Apply CSMA/CA and CSMA/CD mechanism and study their
performance.
• Schedule events and run the program.
PROGRAM:
a) CSMA/CA:
set ns [new Simulator]
#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
}
#Create six nodes
set n0 [$ns node]
set n1 [$ns node]
# next procedure gets two arguments: the name of the # tcp source node, will
be called here "tcp",
# and the name of output file.
proc plotWindow {tcpSource file} {
global ns
set time 0.1
set now [$ns now]
set cwnd [$tcpSource set cwnd_]
OUTPUT:
Fig no : 11.1 OPERTATION OF CSMA/CA USING NS-2
PROGRAM:
b) CSMA/CD
set ns [new Simulator]
#Define different colors for data flows (for NAM)
$ns color 1 Blue
$ns color 2 Red
#Open the Trace files
set file1 [open out.tr w]
set winfile [open WinFile w]
$ns trace-all $file1
#Open the NAM trace file
set file2 [open out.nam w]
$ns namtrace-all $file2
#Define a 'finish' procedure
proc finish {} {
global ns file1 file2
$ns flush-trace
close $file1
close $file2
exec nam out.nam &
exit 0
}
#Create six nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
$n1 color red
$n1 shape box
#Create links between the nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns simplex-link $n2 $n3 0.3Mb 100ms DropTail
$ns simplex-link $n3 $n2 0.3Mb 100ms DropTail
set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail
MAC/Csma/Cd Channel]
#Setup a TCP connection
set tcp [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink/DelAck]
$ns attach-agent $n4 $sink
$ns connect $tcp $sink
$tcp set fid_ 1
$tcp set window_ 8000
$tcp set packetSize_ 552
#Setup a FTP over TCP connection
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ftp set type_ FTP
#Setup a UDP connection
set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]set n3 [$ns node]
$ns attach-agent $n5 $null
$ns connect $udp $null
$udp set fid_ 2
#Setup a CBR over UDP connection
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 0.01mb
$cbr set random_ false
$ns at 0.1 "$cbr start"
$ns at 1.0 "$ftp start"
$ns at 124.0 "$ftp stop"
$ns at 124.5 "$cbr stop"
# next procedure gets two arguments: the name of the # tcp
source node, will be called here "tcp",
# and the name of output file.
proc plotWindow {tcpSource file} {
global ns
set time 0.1
set now [$ns now]
set cwnd [$tcpSource set cwnd_]
set wnd [$tcpSource set window_]
puts $file "$now $cwnd"
$ns at [expr $now+$time] "plotWindow $tcpSource $file"
}
$ns at 0.1 "plotWindow $tcp $winfile"
$ns at 5 "$ns trace-annotate \"packet drop\""
# PPP
$ns at 125.0 "finish"
$ns run
OUTPUT:
RESULT:
Thus, the perform of operation of CSMA/CA and CSMA/CD using
NS2 is implemented and verified.