Nothing Special   »   [go: up one dir, main page]

EC3401 LAB Manual - Network Security - 2022-2023

Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 43

EC3401- Networks and Security Department of ECE 2022 - 2023

INDEX

S. Date Name of the experiment Page Date of sub Marks Staff


No No sign

1. Network Topology - Star, Bus and Ring


Using Trainer Kit

2. Implement the Data Link Layer


framing methods
i) Bit stuffing, (ii) Character stuffing

3. Implementation of Error Detection /


Correction Techniques
(i) CRC, (ii) Hamming code

4. Implementation of Stop and Wait


Protocols

5. Implementation of Go back-N and


Selective Repeat Protocols.

6 Implementation of Distance Vector


. Routing algorithm (Routing Information
Protocol) (Bellman-Ford).

7. Implementation of Link State Routing


algorithm (Open Shortest Path First)
with 5 nodes (Dijkstra's).

8. Data encryption and decryption using


Data Encryption Standard algorithm.

9. Data encryption and decryption using


RSA (Rivest, Shamir and Adleman)
algorithm.

10. Implement Client Server model using


FTP protocol.

11. Implement and realize the Network


Topology - Star, Bus and Ring using
NS2.

12. Implement and perform the operation of


CSMA/CD and CSMA/CA using NS2.

1
EC3401- Networks and Security Department of ECE 2022 - 2023

EC3401 NETWORKS AND SECURITY LTPC


3 0 2 4
LIST OF EXPERIMENTS:
Experiments using C
1. Implement the Data Link Layer framing methods,
i) Bit stuffing, (ii) Character stuffing
2. Implementation of Error Detection / Correction Techniques
i) LRC, (ii) CRC, (iii) Hamming code
3. Implementation of Stop and Wait, and Sliding Window Protocols
4. Implementation of Go back-N and Selective Repeat Protocols.
5. Implementation of Distance Vector Routing algorithm (Routing Information Protocol)
(Bellman-Ford).
6. Implementation of Link State Routing algorithm (Open Shortest Path First) with 5 nodes
(Dijkstra's).
7. Data encryption and decryption using Data Encryption Standard algorithm.
8. Data encryption and decryption using RSA (Rivest, Shamir and Adleman) algorithm.
9. Implement Client Server model using FTP protocol.
Experiments using Tool Command Language
1. Implement and realize the Network Topology - Star, Bus and Ring using NS2.
2. Implement and perform the operation of CSMA/CD and CSMA/CA using NS2.
TOTAL: 30 PERIODS

LIST OF EXPERIMENTS

S.No. CYCLE I
1. Network Topology - Star, Bus and Ring Using Trainer Kit
2. Implement the Data Link Layer framing methods
i) Bit stuffing, (ii) Character stuffing
3. Implementation of Error Detection / Correction Techniques
(i) CRC, (ii) Hamming code
4. Implementation of Stop and Wait Protocols
5. Implementation of Go back-N and Selective Repeat Protocols.
6. Implementation of Distance Vector Routing algorithm (Routing Information
Protocol) (Bellman-Ford).
7. Implementation of Link State Routing algorithm (Open Shortest Path First) with 5
nodes (Dijkstra's).
8. Data encryption and decryption using Data Encryption Standard algorithm.
9. Data encryption and decryption using RSA (Rivest, Shamir and Adleman) algorithm.
10. Implement Client Server model using FTP protocol.

11. Implement and realize the Network Topology - Star, Bus and Ring using NS2.

12. Implement and perform the operation of CSMA/CD and CSMA/CA using NS2.

2
EC3401- Networks and Security Department of ECE 2022 - 2023

EX. NO: 1 Date:


NETWORK TOPOLOGY - STAR, BUS, RING
AIM:

To create scenario and study the performance of network topologies through simulation and using
trainer kit.

APPARATUS REQUIRED

1.LTS-01 trainer kit.


2.2 Computers with win-2K / XP and Ethernet port available on them
3.RJ-45 to RJ-45 LAN connecting cables.
4.L-SIM LAN protocol analyzer and simulator software
5.PC with NS-2 Simulator

THEORY:

Network Topology refers to layout of a network and how different nodes in a network are connected


to each other and how they communicate. Topologies are either physical (the physical layout of
devices on a network) or logical (the way that the signals act on the network media, or the way that
the data passes through the network from one device to the next). This Webopedia Study Guide
describes five of the most common network topologies.
Star Topology : In a star network devices are connected to a central computer, called a hub. Nodes
communicate across the network by passing data through the hub.

Figure 1 : Star Topology


Advantage:  In a star network, one malfunctioning node doesn't affect the rest of the network.
Disadvantage: If the central computer fails, the entire network becomes unusable.
Bus Topology: In networking a bus is the central cable -- the main wire -- that connects all devices on
a local-area network (LAN). It is also called the backbone. This is often used to describe the main
network connections composing the Internet.  Bus networks are relatively inexpensive and easy to
install for small networks. Ethernetsystems use a bus topology.

Figure 2 : Bus Topology


Advantage:  It's easy to connect a computer or device and typically it requires less cable than a star
topology.
Disadvantage: The entire network shuts down if there is a break in the main wire and it can be
difficult to identify the problem if the network shuts down.
Ring Topology: A local-area network (LAN) whose topology is a ring. That is, all of the nodes are
connected in a closed loop. Messages travel around the ring, with each node reading those messages
addressed to it.

Figure 3 : Ring Topology


Advantage: One main advantage to a ring network is that it can span larger distances than other types
of networks, such as bus networks, because each node regenerates messages as they pass through it.

3
EC3401- Networks and Security Department of ECE 2022 - 2023

PROCEDURE:

1. Connect 2 computer LAN ports using RJ-45 to RJ-45 LAN connecting cables provided with the
system to LTS-01 star topology ports.
2. Switch on the LTS-01 & Computers.
3. Run L-SIM software on all the computers, one should be server and othersshould be clients.
4. On the server computer select type of network as LAN and select the topology as STAR, and
select protocol as Stop & Wait & click on create network button.
5. Remote computer details will appear on the computers connected in network, the server will be
able to see all clients and all clients will be able to see only the server.
6. Select the computer to whom data file is to be transferred, by using the load button.
7. File size will appear in the software window, select the packet size, interpacket delay and click
OK.
8. Total packets formed for that file will be indicated on computers.
9. Start the transfer of file, and during file transfer process you can insert errors into data Packets
being transmitted through software window.
10. Verify the formation of error packet and also the process of re-transmission of the error packet
using stop and wait protocol.
11. File transfer from one computer to another will take place.
12. Multiple file transfer between various server-client combinations should be performed to observe
throughput v/s packet size graph on transmitter computer.
13. Close file transfer window and click on protocol analyzer and Network analyzer buttons on
transmitter computer to view details of the log created.
14. Calculate throughput by clicking on Plot graph button.
15. Detailed graph of throughput v/s packet size for the total file transfer activity will appear on graph
window.
16. This plot can be printed by clicking on print button
17. The screen shot of the screen during transmission will look like the below picture.

RESULT:

Thus the network topologies through simulation and using trainer kit was executed and the
output was verified.

4
EC3401- Networks and Security Department of ECE 2022 - 2023

EX. NO: 2 Date:

IMPLEMENT THE DATA LINK LAYER FRAMING METHODS,


I) BIT STUFFING, (II) CHARACTER STUFFING
AIM:

To Implement the Data Link Layer Framing Methods using C complier.

APPARATUS REQUIRED:

1. Personal Computer
2. C Complier

THEORY:

i)Bit Stuffing in Computer Network


The data link layer is responsible for something called Framing, which is the division of stream of bits
from network layer into manageable units (called frames). Frames could be of fixed size or variable
size. In variable-size framing, we need a way to define the end of the frame and the beginning of the
next frame. 
Bit stuffing is the insertion of non information bits into data. Note that stuffed bits should not be
confused with overhead bits. 

Bit Stuffing is a process of inserting an extra bit as 0, once the frame sequence
encountered 5 consecutive 1’s. Given an array, arr[] of size N consisting of 0’s and 1’s, the task is to
return an array after the bit stuffing.

Example of bit stuffing – 


Bit sequence: 110101111101011111101011111110 (without bit stuffing) 
Bit sequence: 110101111100101111101010111110110 (with bit stuffing) 
After 5 consecutive 1-bits, a 0-bit is stuffed. Stuffed bits are marked bold.

5
EC3401- Networks and Security Department of ECE 2022 - 2023

Programme

#include <stdio.h>
#include <string.h>
 
// Function for bit stuffing
void bitStuffing(int N, int arr[])
{
    // Stores the stuffed array
    int brr[30];
 
    // Variables to traverse arrays
    int i, j, k;
    i = 0;
    j = 0;
 
    // Loop to traverse in the range [0, N)
    while (i < N) {
 
        // If the current bit is a set bit
        if (arr[i] == 1) {
           
            // Stores the count of consecutive ones
            int count = 1;
 
            // Insert into array brr[]
            brr[j] = arr[i];
 
            // Loop to check for
            // next 5 bits
            for (k = i + 1;
                 arr[k] == 1 && k < N && count < 5; k++) {
                j++;
                brr[j] = arr[k];
                count++;
 
                // If 5 consecutive set bits
                // are found insert a 0 bit
                if (count == 5) {
                    j++;
                    brr[j] = 0;
                }
                i = k;
            }
        }
 
        // Otherwise insert arr[i] into
        // the array brr[]
        else {
            brr[j] = arr[i];
        }
        i++;
        j++;
    }
 
    // Print Answer
    for (i = 0; i < j; i++)
        printf("%d", brr[i]);
}
 
// Driver Code
int main()

6
EC3401- Networks and Security Department of ECE 2022 - 2023

{
    int N = 6;
    int arr[] = { 1, 1, 1, 1, 1, 1 };
 
    bitStuffing(N, arr);
 
    return 0;
}

Input: N=6,arr[]={1,1,1,1,1,1}
Output: 1111101

(ii) Character stuffing


Same idea as bit-stuffing, but operates on bytes instead of bits. Use reserved characters to
indicate the start and end of a frame. Byte - Stuffing − A byte is stuffed in the message to
differentiate from the delimiter. This is also called character-oriented framing.

Programme

#include<stdio.h>
#include<string.h>
int 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;
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);
getchar();
}

7
EC3401- Networks and Security Department of ECE 2022 - 2023

Output :

Enter characters to be stuffed:welcome


Enter a character that represents starting delimiter:a
Enter a character that represents ending delimiter:b
After stuffing: awelcome.

RESULT:

Thus the implementation of data link layer framing method using bit stuffing and charater
stuffing was executed and the output was verified.

8
EC3401- Networks and Security Department of ECE 2022 - 2023

EX. NO: 3 Date:

IMPLEMENTATION OF ERROR DETECTION / CORRECTION


TECHNIQUES (I) CRC, (II) HAMMING CODE
AIM:

To implement Error detectin and Correctin methods using C Complier.

APPARATUS REQUIRED:

1. Personal Computer
2. C Complier

THEORY:

When sending data from a sender to a receiver, there are possibilities that the data sent
as digital signals may get changed due to noise during the process of sending the data. Due to
this, data received by the receiver may be different from the data sent by the sender. This
change in data bit is called an error and to prevent such an error, the data received by the
receiver is checked using different error detection algorithms. One such algorithm is
the Cyclic Redundancy Check algorithm.

PROGRAM:

// Include headers
#include<stdio.h>
#include<string.h>
// length of the generator polynomial
#define N strlen(gen_poly)
// data to be transmitted and received
char data[28];
// CRC value
char check_value[28];
// generator polynomial
char gen_poly[10];
// variables
int data_length,i,j;
// function that performs XOR operation
void XOR(){
// if both bits are the same, the output is 0
// if the bits are different the output is 1
for(j = 1;j < N; j++)
check_value[j] = (( check_value[j] == gen_poly[j])?'0':'1');

}
// Function to check for errors on the receiver side
void receiver(){
// get the received data
printf("Enter the received data: ");
scanf("%s", data);
printf("\n-----------------------------\n");
printf("Data received: %s", data);
// Cyclic Redundancy Check
crc();

9
EC3401- Networks and Security Department of ECE 2022 - 2023

// Check if the remainder is zero to find the error


for(i=0;(i<N-1) && (check_value[i]!='1');i++);
if(i<N-1)
printf("\nError detected\n\n");
else
printf("\nNo error detected\n\n");
}

void crc(){
// initializing check_value
for(i=0;i<N;i++)
check_value[i]=data[i];
do{
// check if the first bit is 1 and calls XOR function
if(check_value[0]=='1')
XOR();
// Move the bits by 1 position for the next computation
for(j=0;j<N-1;j++)
check_value[j]=check_value[j+1];
// appending a bit from data
check_value[j]=data[i++];
}while(i<=data_length+N-1);
// loop until the data ends
}

int main()
{
// get the data to be transmitted
printf("\nEnter data to be transmitted: ");
scanf("%s",data);
printf("\n Enter the Generating polynomial: ");
// get the generator polynomial
scanf("%s",gen_poly);
// find the length of data
data_length=strlen(data);
// appending n-1 zeros to the data
for(i=data_length;i<data_length+N-1;i++)
data[i]='0';
printf("\n----------------------------------------");
// print the data with padded zeros
printf("\n Data padded with n-1 zeros : %s",data);
printf("\n----------------------------------------");
// Cyclic Redundancy Check
crc();
// print the computed check value
printf("\nCRC or Check value is : %s",check_value);
// Append data with check_value(CRC)
for(i=data_length;i<data_length+N-1;i++)
data[i]=check_value[i-data_length];
printf("\n----------------------------------------");
// printing the final data to be sent
printf("\n Final data to be sent : %s",data);
printf("\n----------------------------------------\n");
// Calling the receiver function to check errors
receiver();

10
EC3401- Networks and Security Department of ECE 2022 - 2023

return 0;
}

Output
Uncorrupted data
Enter data to be transmitted: 1001101
Enter the Generating polynomial: 1011
----------------------------------------
Data padded with n-1 zeros : 1001101000
----------------------------------------
CRC or Check value is : 101
----------------------------------------
Final data to be sent : 1001101101
----------------------------------------
Enter the received data: 1001101101
-----------------------------
Data received: 1001101101
No error detected

Corrupted data received


Enter data to be transmitted: 1001101
Enter the Generating polynomial: 101
----------------------------------------
Data padded with n-1 zeros : 100110100
----------------------------------------
CRC or Check value is : 11
----------------------------------------
Final data to be sent : 100110111
----------------------------------------
Enter the received data: 100110110
-----------------------------
Data received: 100110110
Error detected
Hamming code is a set of error-correction codes that can be used to detect and correct the
errors that can occur when the data is moved or stored from the sender to the receiver. It is
a technique developed by R.W. Hamming for error correction. Redundant bits – Redundant
bits are extra binary bits that are generated and added to the information-carrying bits of data
transfer to ensure that no bits were lost during the data transfer. The number of redundant bits
can be calculated using the following formula:
2^r ≥ m + r + 1
where, r = redundant bit, m = data bit
Suppose the number of data bits is 7, then the number of redundant bits can be calculated
using: = 2^4 ≥ 7 + 4 + 1 Thus, the number of redundant bits= 4 Parity bits.  A parity bit is a
bit appended to a data of binary bits to ensure that the total number of 1’s in the data is even
or odd. Parity bits are used for error detection. There are two types of parity bits:
1.Even parity bit: In the case of even parity, for a given set of bits, the number of 1’s are
counted. If that count is odd, the parity bit value is set to 1, making the total count of
occurrences of 1’s an even number. If the total number of 1’s in a given set of bits is already
even, the parity bit’s value is 0.
2.Odd Parity bit – In the case of odd parity, for a given set of bits, the number of 1’s are
counted. If that count is even, the parity bit value is set to 1, making the total count of
occurrences of 1’s an odd number. If the total number of 1’s in a given set of bits is already
odd, the parity bit’s value is 0.

11
EC3401- Networks and Security Department of ECE 2022 - 2023

Programme

//HAMMING CODE for error detection and correction


#include<stdio.h>
int main()
{
int a[4],b[4],r[3], s[3],i,q[3];
printf("\nenter 4 bit data word:\n");
for(i=3;i>=0;i--)
{
scanf("%d",&a[i]);
}
r[0]=(a[2]+a[1]+a[0])%2;
r[1]=(a[2]+a[1]+a[3])%2;
r[2]=(a[0]+a[1]+a[3])%2;

printf("\n\nthe 7bit hamming code word: \n");


for(i=3;i>=0;i--)
{
printf("%d\t",a[i]);
}
for(i=2;i>=0;i--)
{
printf("%d\t",r[i]);
}
printf("\n");
printf("\nenter the 4bit recieved word: ");

for(i=3;i>=0;i--)
scanf("%d",&b[i]);

//calculating syndrome bits


s[0]= (b[2]+b[1]+b[0]+r[0])%2;
s[1]= (b[3]+b[2]+b[1]+r[1])%2;
s[2]= (b[0]+b[1]+b[3]+r[2])%2;
printf("\nsyndrome is: \n");

for(i=2; i>=0;i--)
{
printf("%d",s[i]);
}
if((s[2]==0) && (s[1]==0) && (s[0]==0))
printf("\n RECIEVED WORD IS ERROR FREE\n");
if((s[2]==1) && (s[1]==0) && (s[0]==1))
printf("\nrecieved word is error with error in 1bit(b0) position from right\n");
if((s[2]==1) && (s[1]==1) && (s[0]==1))
printf("\nrecieved word is error with error in 2bit(b1) position from right\n");
if((s[2]==0) && (s[1]==1) && (s[0]==1))
printf("\nrecieved word is error with error in 3bit(b2) position from right\n");
if((s[2]==1) && (s[1]==1) && (s[0]==0))
printf("\nrecieved word is error with error in 4bit(b3) position from right\n");
return(1);
}
//End of Hamming code program

OUTPUT
enter 4 bit data word:
1
0
1

12
EC3401- Networks and Security Department of ECE 2022 - 2023

1
1
the 7bit hamming code word:
1 0 1 1 1 0 0

enter the 4bit recieved word:


1
0
1
1
1
0syndrome is:
000
RECIEVED WORD IS ERROR FREE

RESULT:
Thus the implementation of Error Detection and Error Correction using CRC and
Hamming code was executed and the output was verified.

13
EC3401- Networks and Security Department of ECE 2022 - 2023

EX. NO: 4 Date:

IMPLEMENTATION OF DATA ENCRYPTION AND DECRYPTION

AIM:

To write a java program to implement the file encryption and decryption using java.

REQUIREMENTS:

Java Software

ALGORITHM:

Step 1: Start the process.


Step 2: To create the encrypt file for encrypt the data from created oir.txt by using key value like
integer, to be added with original character value and store into encr.txt file.
Step 3: To create the decrypt file for decrypt the data from created encr.txt file by using key value like
integer to be subtracted from original character value and store into decr.txt file.
Step 4: Create the FileInputStreamoblect for reading the information from the given file name using
FileInputStream class and its constructer with file name.
Step 5: By FileOutputstream object for writing the information into the given file name using
FileOutputStream class and its constructor with file name.
Step 6: Stop the process

PROGRAM:

Encrypt.java:
import java.io.*;
class encrypt
{
public static void main(String args[]) throws Exception
{
DataInputStream in= new DataInputStream(System.in);
FileInputStream f1=new FileInputStream(“ori.txt”);
FileOutputStream f2=new FileOutputStream(“encr.txt”);
int a, key, a1;
try
{
System.out.println(“Enter the key value for Encryption”);
key= Integer.parseInt(in.readLine());
a=f1.read();
while(a!=-1)
{
a1=a+key;
f2.write(a1);
a=f1.read();
}
System.out.println(“the Message was successfully Encrypted”);
f1.close();
f2.close();

14
EC3401- Networks and Security Department of ECE 2022 - 2023

}
catch(Exception e)
{
System.out.println(e);
}
}
}

Decrypt.java:

import java.io.*;
class decrypt
{
public static void main(String args[]) throws Exception
{
DataInputStream in=new DataInputStream(System.in);
FileInputStream f1=new FileInputStream(“encr.txt”);
FileOutputStream f2=new FileOutputStream(“decr.txt”);
int a, key, a1
try
{
System.out.println(“Enter the key value for decryption”);
key=Integer.parseInt(in.readLine());
a=f1.read();
while(a!=-1)
{
a1=a-key;
f2.write(a1);
a=f1.read();
}
System.out.println(“The Message was successfully decrypted”);
f1.close();
f2.close();
}
catch(Exception e)
{
System.out.printlln(e);
}
}
}

15
EC3401- Networks and Security Department of ECE 2022 - 2023

OUTPUT:

RESULT:
Thus the implementation of the file encryption and decryption using java was
executed and the output was verified.

16
EC3401- Networks and Security Department of ECE 2022 - 2023

EX. NO: 5 Date:

DATA ENCRYPTION AND DECRYPTION USING RSA


(RIVEST, SHAMIR AND ADLEMAN) ALGORITHM.
AIM:

To implement data encryptin and decryption using RSA algorithm.

APPARTUS REQUIRED:

1.Personal computer
2. C Complier

PROGRAM

#include<stdio.h>
#include<math.h>
void encrypt();
void decrypt();
long int findGCD(long int, long int);
long int multipicative_inverse(long int, long int);
void key_pair(long int e, long int n, long int d) {
printf("\nEncryption key(e,n):%ld\t%ld\n", e, n);
printf("\nDecryption key(d,n):%ld\t%ld\n", d, n);
}
void encrypt() {
long int pt, p, q, n, fn, e = 2, temp, d, ct;
printf("Enter your message to encrypt:\n");
scanf("%d", & pt);
printf("Enter two prime numbers p and q:\n");
scanf("%ld %ld", & p, & q);
n = p * q;
fn = (p - 1) * (q - 1);
temp = findGCD(e, fn);
while (temp != 1) {
e++;
temp = findGCD(e, fn);
//printf("e=%ld\ttemp=%d\t",e,temp);
}
//printf("\ne=%ld\n",e);
d = multipicative_inverse(fn, e);
if (d == 0) {
printf("\nrsa is not possible for given p and q.\n");
exit(0);
}
ct = fmod(pow(pt, e), n);
key_pair(e, n, d);
printf("\nencrypted text:\t%ld\n", ct);

}
void decrypt() {
long int pt, d, ct, n;
printf("Enter message to decrypt:\n");
scanf("%ld", & ct);
printf("Enter key pair(d,n):\n");
scanf("%ld %ld", & d, & n);
pt = fmod(pow(ct, d), n);

17
EC3401- Networks and Security Department of ECE 2022 - 2023

printf("Decrypted message:\t%ld", pt);


}
long int multipicative_inverse(long int m, long int b) {
long int a1 = 1, a2 = 0, a3 = m, b1 = 0, b2 = 1, b3 = b, t1, t2, t3, q;
top:
if (b3 == 0) return 0;
else if (b3 == 1) {
if (b2 < 0) return (b2 + m);
else return b2;
}
q = a3 / b3;
t1 = b1;
t2 = b2;
t3 = b3;
b1 = a1 - (q * b1);
b2 = a2 - (q * b2);
b3 = a3 - (q * b3);
a1 = t1;
a2 = t2;
a3 = t3;
//printf("\nb2=%ld\n",b2);
goto top;
}
long int findGCD(long int e, long int fn) {
long int c = e, d = fn;
long int r;
while (d != 0) {
r = c % d;
c = d;
d = r;
}
return c;
}
int main() {
int choice;
while (1) {
printf("\nEnter your choice:\t1.Encrypt\t2.Decrypt\t3.Exit\n");
scanf("%d", & choice);
switch (choice) {
case 1: {
encrypt();
break;
}
case 2: {
decrypt();
break;
}
case 3: {
break;
}
default: {
printf("\nInvalid choice,Enter valid choice.\n");
}
}
if (choice == 3)
break;
}
return 0;
}

18
EC3401- Networks and Security Department of ECE 2022 - 2023

OUTPUT

Enter your choice: 1.Encrypt 2.Decrypt 3.Exit


1
Enter your message to encrypt:
12
Enter two prime numbers p and q:
37
Encryption key(e,n):5 21
Decryption key(d,n):5 21
encrypted text:3
Enter your choice: 1.Encrypt 2.Decrypt 3.Exit
2
Enter message to decrypt:
3
Enter key pair(d,n):
5 21
Decrypted message: 12

RESULT:

Thus the implementation of Data Encryption and Decryption using RSA


Algorithm was executed and the output was verified.

19
EC3401- Networks and Security Department of ECE 2022 - 2023

EX. NO: Date:

IMPLEMENTATION OF LINK STATE ROUTING ALGORITHM


(OPEN SHORTEST PATH FIRST) WITH 5 NODES (DIJKSTRA'S)

AIM:

To implement link stage routing algorithm using C complier.

APPARTUS REQUIRED:

1.Personal computer
2. C Complier

PROGRAM

#include <stdio.h>
#include <string.h>
int main()
{
int count,src_router,i,j,k,w,v,min;
int cost_matrix[100][100],dist[100],last[100];
int flag[100];
printf("\n Enter the no of routers");
scanf("%d",&count);
printf("\n Enter the cost matrix values:");
for(i=0;i<count;i++)
{
for(j=0;j<count;j++)
{
printf("\n%d->%d:",i,j);
scanf("%d",&cost_matrix[i][j]);
if(cost_matrix[i][j]<0)cost_matrix[i][j]=1000;
}
}
printf("\n Enter the source router:");
scanf("%d",&src_router);
for(v=0;v<count;v++)
{
flag[v]=0;
last[v]=src_router;
dist[v]=cost_matrix[src_router][v];
}
flag[src_router]=1;
for(i=0;i<count;i++)
{
min=1000;

20
EC3401- Networks and Security Department of ECE 2022 - 2023

for(w=0;w<count;w++)
{
if(!flag[w])
if(dist[w]<min)
{
v=w;
min=dist[w];
}
}
flag[v]=1;
for(w=0;w<count;w++)
{
if(!flag[w])
if(min+cost_matrix[v][w]<dist[w])
{
dist[w]=min+cost_matrix[v][w];
last[w]=v;
}
}
}
for(i=0;i<count;i++)
{
printf("\n%d==>%d:Path taken:%d",src_router,i,i);
w=i;
while(w!=src_router)
{
printf("\n<--%d",last[w]);w=last[w];
}
printf("\n Shortest path cost:%d",dist[i]);
}
}

OUTPUT:

Enter the no of routers2


Enter the cost matrix values:
0->0:0 1 2
0->1:
1->0:
1->1:
123
Enter the source router:2
2==>0:Path taken:0
<--2
Shortest path cost:0
2==>1:Path taken:1
<--2
Shortest path cost:02

21
EC3401- Networks and Security Department of ECE 2022 - 2023

EX. NO: Date:

IMPLEMENT CLIENT SERVER MODEL USING FTP PROTOCOL.

AIM:

To implement client server model using FTP Protocol.

APPARTUS REQUIRED:

1.Personal computer
2. C Complier

ALGORITHM:

SERVER:

    STEP 1: Start
    STEP 2: Declare the variables for the socket
    STEP 3: Specify the family, protocol, IP address and port number
    STEP 4: Create a socket using socket() function
    STEP 5: Bind the IP address and Port number
    STEP 6: Listen and accept the client’s request for the connection
    STEP 7: Establish the connection with the client
    STEP 8: Close the socket
    STEP 9: Stop

CLIENT:

    STEP 1: Start
    STEP 2: Declare the variables for the socket
    STEP 3:  Specify the family, protocol, IP address and port number
    STEP 4: Create a socket using socket() function
    STEP 5: Call the connect() function
    STEP 6: Close the socket
    STEP 7: Stop

PROGRAMME

SERVER:

#include<stdio.h>
#include<arpa/inet.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#define SERV_TCP_PORT 5035
#define MAX 60

22
EC3401- Networks and Security Department of ECE 2022 - 2023

int i, j, tem;
char buff[4096], t;
FILE *f1;
int main(int afg, char *argv)
{
       int sockfd, newsockfd, clength;
       struct sockaddr_in serv_addr,cli_addr;
       char t[MAX], str[MAX];
       strcpy(t,"exit");
       sockfd=socket(AF_INET, SOCK_STREAM,0);
       serv_addr.sin_family=AF_INET;
       serv_addr.sin_addr.s_addr=INADDR_ANY;
       serv_addr.sin_port=htons(SERV_TCP_PORT);
       printf("\nBinded");
       bind(sockfd,(struct sockaddr*)&serv_addr, sizeof(serv_addr));
       printf("\nListening...");
       listen(sockfd, 5);
       clength=sizeof(cli_addr);
       newsockfd=accept(sockfd,(struct sockaddr*) &cli_addr,&clength);
       close(sockfd);
       read(newsockfd, &str, MAX);
       printf("\nClient message\n File Name : %s\n", str);
       f1=fopen(str, "r");
       while(fgets(buff, 4096, f1)!=NULL)
       {
            write(newsockfd, buff,MAX);
            printf("\n");
       }
       fclose(f1);
       printf("\nFile Transferred\n");
       return 0;
}

CLIENT:

#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<netdb.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
#define SERV_TCP_PORT 5035
#define MAX 60
int main(int arg,char*argv[])
{
       int sockfd,n;
       struct sockaddr_in serv_addr;
       struct hostent*server;
       char send[MAX],recvline[MAX],s[MAX],name[MAX];
       sockfd=socket(AF_INET,SOCK_STREAM,0);
       serv_addr.sin_family=AF_INET;
       serv_addr.sin_addr.s_addr=inet_addr("127.0.0.1");
       serv_addr.sin_port=htons(SERV_TCP_PORT);
       connect(sockfd,(struct sockaddr*)&serv_addr,sizeof(serv_addr));
       printf("\nEnter the source file name : \n");
       scanf("%s",send);
       write(sockfd,send,MAX);
       while((n=read(sockfd,recvline,MAX))!=0)

23
EC3401- Networks and Security Department of ECE 2022 - 2023

       {
          printf("%s",recvline);
       }
       close(sockfd);
       return 0;
}
OUTPUT: SERVER

CLIENT

RESULT:   
            Thus the program for FTP client server was executed and the output was verified.

24
EC3401- Networks and Security Department of ECE 2022 - 2023

EX. NO: Date:

STUDY OF NETWORK SIMULATOR (NS)


AIM:

To study ns2 in detail.

INTRODUCTION:

Network Simulator (Version 2), widely known as NS2, is simply an eventdriven simulation tool that
has proved useful in studying the dynamic nature of communication networks. Simulation of wired as
well as wireless network functions and protocols (e.g., routing algorithms, TCP, UDP) can be done
using NS2. In general, NS2 provides users with a way of specifying such network protocols and
simulating their corresponding behaviors. Due to its flexibility and modular nature, NS2 has gained
constant popularity in the networking research community since its birth in 1989. Ever since, several
revolutions and revisions have marked the growing maturity of the tool, thanks to substantial
contributions from the players in the field. Among these are the University of California and Cornell
University who developed the REAL network simulator,1 the foundation which NS is based on.
Since 1995 the Defense Advanced Research Projects Agency (DARPA) supported development of
NS through the Virtual InterNetwork Testbed (VINT) project [9].2 Currently the National Science
Foundation (NSF) has joined the ride in development. Last but not the least, the group of Researchers
and developers in the community are constantly working to keep NS2 strong and versatile.

Basic Architecture

Figure 1: Basic architecture of NS


Figure 2.1 shows the basic architecture of NS2. NS2 provides users with an executable command ns
which takes on input argument, the name of a Tcl simulation scripting file. Users are feeding the name
of a Tcl simulation script (which sets up a simulation) as an input argument of an NS2 executable
command ns.
In most cases, a simulation trace file is created, and is used to plot graph and/or to create animation.
NS2 consists of two key languages: C++ and Object-oriented Tool Command Language (OTcl).
While the C++ defines the internal mechanism (i.e., a backend) of the simulation objects, the OTcl
sets up simulation by assembling and configuring the objects as well as scheduling discrete events
(i.e., a frontend).
The C++ and the OTcl are linked together using TclCL. Mapped to a C++ object, variables in the
OTcl domains are sometimes referred to as handles. Conceptually, a handle (e.g., n as a Node handle)
is just a string (e.g.,_o10) in the OTcl domain, and does not contain any functionality. Instead, the
functionality (e.g., receiving a packet) is defined in the mapped C++ object (e.g., of class Connector).
In the OTcl domain, a handle acts as a frontend which interacts with users and other OTcl objects. It
may defines its own procedures and variables to facilitate the interaction. Note that the member
procedures and variables in the OTcl domain are called instance procedures (instprocs) and instance
variables (instvars), respectively. Before proceeding further, the readers are encouraged to learn C++

25
EC3401- Networks and Security Department of ECE 2022 - 2023

and OTcl languages. We refer the readers to [14] for the detail of C++, while a brief tutorial of Tcl
and OTcl tutorial are given in Appendices A.1 and A.2, respectively.
NS2 provides a large number of built-in C++ objects. It is advisable to use these C++ objects to set up
a simulation using a Tcl simulation script. However, advance users may find these objects
insufficient. They need to develop their own C++ objects, and use a OTcl configuration interface to
put together these objects. After simulation, NS2 outputs either text-based or animation-based
simulation results. To interpret these results graphically and interactively, tools such as NAM
(Network AniMator) and XGraph are used. To analyze a particular behaviour of the network, users
can extract a relevant subset of text-based data and transform it to a more conceivable presentation.

CONCEPT OVERVIEW:

NS uses two languages because simulator has two different kinds of things it needs to do. On one
hand,detailed simulations of protocols requires a systems programming language which can
efficiently manipulate bytes, packet headers, and implement algorithms that run over large data sets.
For these tasks run-time speed is important and turn-around time (run simulation, find bug, fix bug,
recompile, re-run) is less important. On the other hand, a large part of network research involves
slightly varying parameters or configurations, or quickly exploring a number of scenarios.
In these cases, iteration time (change the model and re-run) is more important. Since configuration
runs once (at the beginning of the simulation), run-time of this part of the task is less important. ns
meets both of these needs with two languages, C++ and OTcl.

SIMULATOR INITIALIZATION:

When a new simulation object is created in tcl, the initialization procedure performs the following
operations:
• initialize the packet format (calls create_packetformat)
• create a scheduler (defaults to a calendar scheduler)
• create a “null agent” (a discard sink used in various places)

SCHEDULERS AND EVENTS:

The simulator is an event-driven simulator. There are presently four schedulers available in the
simulator, each of which is implemented using a different data structure: a simple linked-list, heap,
calendar queue (default), and a special type call called “real-time”. Each of these are described below.
The scheduler runs by selecting the next earliest event, executing it to completion, and returning to
execute the next event.Unit of time used by scheduler is seconds. Presently, the simulator is single-
threaded, and only one event in execution at any given time. If more than one event are scheduled to
execute at the same time, their execution is performed on the first scheduled – first dispatched
manner. Simultaneous events are not reordered anymore by schedulers (as it was in earlier versions)
and all schedulers should yeild the same order of dispatching given the same input.

NODE BASICS:

The basic primitive for creating a node is set ns [new Simulator] $ns node. The instance procedure
node constructs a node out of more simple classifier objects (Section 5.4). The Node itself is a
standalone class in OTcl. However, most of the components of the node are themselves TclObjects.
The typical structure of a (unicast) node is as shown in Figure 5.1. This simple structure consists of
two TclObjects: an address classifer (classifer_) and a port classifier (dmux_). The function of these
classifiers is to distribute incoming packets to the correct agent or outgoing link.
All nodes contain at least the following components:
• an address or id_, monotonically increasing by 1 (from initial value 0) across the simulation
namespace as nodes are created,
• a list of neighbors (neighbor_)

BASIC COMMANDS IN NS2:

Set ns [new Simulator]: generates an NS simulator object instance, and assigns it to variable ns. The
"Simulator" object has member functions that do the following:

26
EC3401- Networks and Security Department of ECE 2022 - 2023

Create compound objects such as nodes and links (described later)


Connect network component objects created (ex. attach-agent)

Set network component parameters (mostly for compound objects)


Create connections between agents (ex. make connection between a "tcp" and "sink")

Specify NAM display options

Most of member functions are for simulation setup (referred to as plumbing functions in the Overview
section) and scheduling, however some of them are for the NAM display. The "Simulator" object
member function implementations are located in the "ns-2/tcl/lib/ns-lib.tcl" file.
$ns color fid color: is to set color of the packets for a flow specified by the flow id (fid). This member
function of "Simulator" object is for the NAM display, and has no effect on the actual simulation.
$ns namtrace-all file-descriptor: This member function tells the simulator to record simulation traces
in NAM input format. It also gives the file name that the trace will be written to later by the command
$ns flush-trace. Similarly, the member function trace-all is for recording the simulation trace in a
general format.
proc finish {}: is called after this simulation is over by the command $ns at 5.0 "finish". In this
function, post-simulation processes are specified.
set n0 [$ns node]: The member function node creates a node. A node in NS is compound object made
of address and port classifiers (described in a later section). Users can create a node by separately
creating an address and a port classifier objects and connecting them together. However, this member
function of Simulator object makes the job easier. To see how a node is created, look at the files: "ns-
2/tcl/libs/ns-lib.tcl"andns-2/tcl/libs/ns-node.tcl".
$ns duplex-link node1 node2 bandwidth delay queue-type: creates two simplex links of specified
bandwidth and delay, and connects the two specified nodes. In NS, the output queue of a node is
implemented as a part of a link, therefore users should specify the queue-type when creating links. In
the above simulation script, DropTail queue is used. If the reader wants to use a RED queue, simply
replace the word DropTail with RED. The NS implementation of a link is shown in a later section.
Like a node, a link is a compound object, and users can create its sub-objects and connect them and
the nodes. Link source codes can be found in "ns-2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/ns-link.tcl"
files. One thing to note is that you can insert error modules in a link component to simulate a lossy
link (actually users can make and insert any network objects). Refer to the NS documentation to find
out how to do this.
$ns queue-limit node1 node2 number: This line sets the queue limit of the two simplex links that
connect node1 and node2 to the number specified. At this point, the authors do not know how many
of these kinds of member functions of Simulator objects are available and what they are. Please take a
look at "ns-2/tcl/libs/ns-lib.tcl" and "ns-2/tcl/libs/ns-link.tcl", or NS.
$ns duplex-link-op node1 node2 ...: The next couple of lines are used for the NAM display. To see the
effects of these lines, users can comment these lines out and try the simulation.
Now that the basic network setup is done, the next thing to do is to setup traffic agents such as TCP
and UDP, traffic sources such as FTP and CBR, and attach them to nodes and agents respectively.
set tcp [new Agent/TCP]: This line shows how to create a TCP agent. But in general, users can create
any agent or traffic sources in this way. Agents and traffic sources are in fact basic objects (not
compound objects), mostly implemented in C++ and linked to OTcl. Therefore, there are no specific
Simulator object member functions that create these object instances.
To create agents or traffic sources, a user should know the class names these objects (Agent/TCP,
Agnet/TCPSink, Application/FTP and so on). This information can be found in the NS documentation
or partly in this documentation. But one shortcut is to look at the "ns2/tcl/libs/ns-default.tcl" file. This
file contains the default configurable parameter value settings for available network objects.
Therefore, it works as a good indicator of what kind of network objects are available in NS and what
are the configurable parameters.
$ns attach-agent node agent: The attach-agent member function attaches an agent object created to a
node object. Actually, what this function does is call the attach member function of specified node,
which attaches the given agent to itself. Therefore, a user can do the same thing by, for example, $n0
attach $tcp. Similarly, each agent object has a member function.
$ns connect agent1 agent2: After two agents that will communicate with each other are created, the
next thing is to establish a logical network connection between them. This line establishes a network
connection by setting the destination address to each others' network and port address pair.

27
EC3401- Networks and Security Department of ECE 2022 - 2023

Assuming that all the network configuration is done, the next thing to do is write a simulation
scenario (i.e. simulation scheduling). The Simulator object has many scheduling member functions.
However, the one that is mostly used in the following:$ns at time "string": This member function of a
Simulator object makes the scheduler (scheduler_ is the variable that points the scheduler object
created by [new Scheduler] command at the beginning of the script) to schedule the execution of the
specified string at given simulation time.
After all network configuration, scheduling and post-simulation procedure specifications are done, the
only thing left is to run the simulation. This is done by $ns run.

RESULT:

28
EC3401- Networks and Security Department of ECE 2022 - 2023

EX. NO: Date:


SIMULATION OF STOP AND WAIT
PROTOCOL
AIM:
To Simulate and to study Stop and Wait protocol

SOFTWARE REQUIREMENTS:

NS-2 Simulator

THEORY:

Stop and Wait is a reliable transmission flow control protocol. This protocol works only in
Connection Oriented (Point to Point) Transmission. The Source node has window size of ONE. After
transmission of a frame the transmitting (Source) node waits for an Acknowledgement from the
destination node. If the transmitted frame reaches the destination without error, the destination
transmits a positive acknowledgement. If the transmitted frame reaches the Destination with error, the
receiver destination does not transmit an acknowledgement. If the transmitter receives a positive
acknowledgement it transmits the next frame if any. Else if its acknowledgement receive timer
expires, it retransmits the same frame.
1. Start with the window size of 1 from the transmitting (Source) node
2. After transmission of a frame the transmitting (Source) node waits for a reply (Acknowledgement)
from the receiving (Destination) node.
3. If the transmitted frame reaches the receiver (Destination) without error, the receiver (Destination)
transmits a Positive Acknowledgement.
4. If the transmitted frame reaches the receiver (Destination) with error, the receiver (Destination) do
not transmit acknowledgement.
5. If the transmitter receives a positive acknowledgement it transmits the next frame if any. Else if
the transmission timer expires, it retransmits the same frame again.
6. If the transmitted acknowledgment reaches the Transmitter (Destination) without error, the
Transmitter (Destination) transmits the next frame if any.
7. If the transmitted frame reaches the Transmitter (Destination) with error, the Transmitter
(Destination) transmits the same frame.
8. This concept of the Transmitting (Source) node waiting after transmission for a reply from the
receiver is known as STOP and WAIT.

29
EC3401- Networks and Security Department of ECE 2022 - 2023

Algorithm

#PROGRAM FOR STOP AND WAIT:

#send packets one by one


set ns [new Simulator]
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 color "purple"
$n1 color "purple"
$n2 color "violet"
$n3 color "violet"
$n4 color "chocolate"
$n5 color "chocolate"
$n0 shape box ;
$n1 shape box ;
$n2 shape box ;
$n3 shape box ;
$n4 shape box ;
$n5 shape box ;
$ns at 0.0 "$n0 label SYS0"
$ns at 0.0 "$n1 label SYS1"
$ns at 0.0 "$n2 label SYS2"
$ns at 0.0 "$n3 label SYS3"
$ns at 0.0 "$n4 label SYS4"
$ns at 0.0 "$n5 label SYS5"
set nf [open stopwait.nam w]
$ns namtrace-all $nf
set f [open stopwait.tr w]
$ns trace-all $f
$ns duplex-link $n0 $n2 0.2Mb 20ms DropTail
$ns duplex-link-op $n0 $n2 orient right-down
$ns queue-limit $n0 $n2 10
$ns duplex-link $n1 $n2 0.2Mb 20ms DropTail
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link $n2 $n3 0.2Mb 20ms DropTail
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link $n3 $n4 0.2Mb 20ms DropTail
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link $n3 $n5 0.2Mb 20ms DropTail
$ns duplex-link-op $n3 $n5 orient right-down
Agent/TCP set_nam_tracevar_true
set tcp [new Agent/TCP]
$tcp set window 1
$tcp set maxcwnd 1
$tcp set fid 1
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n5 $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns add-agent-trace $tcp tcp
$ns monitor-agent-trace $tcp

30
EC3401- Networks and Security Department of ECE 2022 - 2023

$tcp tracevar cwnd


$ns at 0.1 "$ftp start"
$ns at 0.53 "$ns queue-limit $n3 $n5 0"
$ns at 0.80 "$ns queue-limit $n3 $n5 5"
$ns at 2.0 "$ns detach-agent $n0 $tcp ; $ns detach-agent $n5 $sink"
$ns at 2.5 "finish"
#$ns at 0.0 "$ns trace-annotate \"STOPWAIT\""
$ns at 0.01 "$ns trace-annotate \"FTP starts at 0.01\""
$ns at 0.10 "$ns trace-annotate \"Send Request SYS0 to SYS5\""
$ns at 0.18 "$ns trace-annotate \"Receive Request SYS5 to SYS0\""
$ns at 0.24 "$ns trace-annotate \"Send Packet_0 SYS0 to SYS5\""
$ns at 0.42 "$ns trace-annotate \"Receive Ack_0\""
$ns at 0.48 "$ns trace-annotate \"Send Packet_1\""
$ns at 0.60 "$ns trace-annotate \"Disconnect N2 So loss the packet1\""
$ns at 0.67 "$ns trace-annotate \"Waiting for Ack_1\""
$ns at 0.95 "$ns trace-annotate \"Send Packet_1 again\""
$ns at 1.95 "$ns trace-annotate \"Deattach SYS3,Packet_1 again\""
$ns at 2.09 "$ns trace-annotate \"Receive Ack_1\""
$ns at 2.10 "$ns trace-annotate \"SEnd Packet_2\""
$ns at 2.38 "$ns trace-annotate \"Receive Ack_2\""
$ns at 2.5 "$ns trace-annotate \"FTP stops\""
proc finish {} {
global ns nf
$ns flush-trace
close $nf
#puts"filtering..."
#exec tclsh../bin/namfilter.tcl stopwait.nam
#puts "running nam ..."
exec nam stopwait.nam &
exit 0
}
$ns run

OUTPUT:

RESULT:

31
EC3401- Networks and Security Department of ECE 2022 - 2023

EX. NO: Date:

SIMULATION OF GOBACK N PROTOCAL

AIM:
To Simulate and to study of Go Back N protocol

SOFTWARE REQUIREMENTS:
NS-2 Simulator

THEORY: Go Back N is a connection oriented transmission. The sender transmits the frames
continuously. Each frame in the buffer has a sequence number starting from 1 and increasing up to the
window size. The sender has a window i.e. a buffer to store the frames. This buffer size is the number
of frames to be transmitted continuously. The size of the window depends on the protocol designer.

OPERATIONS:

1. A station may send multiple frames as allowed by the window size.


2. Receiver sends an ACK i if frame i has an error. After that, the receiver discards all incoming
frames until the frame with error is correctly retransmitted.
3. If sender receives an ACK i it will retransmit frame i and all packets i+1, i+2,... which have been
sent, but not been acknowledged

ALGORITHM FOR GO BACK N

1. The source node transmits the frames continuously.


2. Each frame in the buffer has a sequence number starting from 1 and increasing up to the window
size.
3. The source node has a window i.e. a buffer to store the frames. This buffer size is the number of
frames to be transmitted continuously.
4. The size of the window depends on the protocol designer.
5. For the first frame, the receiving node forms a positive acknowledgement if the frame is received
without error.
6. If subsequent frames are received without error (up to window size) cumulative positive
acknowledgement is formed.
7. If the subsequent frame is received with error, the cumulative acknowledgment error-free frames
are transmitted. If in the same window two frames or more frames are received with error, the
second and the subsequent error frames are neglected. Similarly even the frames received without
error after the receipt of a frame with error are neglected.
8. The source node retransmits all frames of window from the first error frame.
9. If the frames are errorless in the next transmission and if the acknowledgment is error free, the
window slides by the number of error-free frames being transmitted.
10.If the acknowledgment is transmitted with error, all the frames of window at source are
retransmitted, and window doesn’t slide.
11.This concept of repeating the transmission from the first error frame in the window is called as
GOBACKN transmission flow control protocol.

32
EC3401- Networks and Security Department of ECE 2022 - 2023

# PROGRAM FOR GOBACK N:

#send packets one by one


set ns [new Simulator]
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 color "purple"
$n1 color "purple"
$n2 color "violet"
$n3 color "violet"
$n4 color "chocolate"
$n5 color "chocolate"
$n0 shape box ;
$n1 shape box ;
$n2 shape box ;
$n3 shape box ;
$n4 shape box ;
$n5 shape box ;
$ns at 0.0 "$n0 label SYS0"
$ns at 0.0 "$n1 label SYS1"
$ns at 0.0 "$n2 label SYS2"
$ns at 0.0 "$n3 label SYS3"
$ns at 0.0 "$n4 label SYS4"
$ns at 0.0 "$n5 label SYS5"
set nf [open goback.nam w]
$ns namtrace-all $nf
set f [open goback.tr w]
$ns trace-all $f
$ns duplex-link $n0 $n2 1Mb 20ms DropTail
$ns duplex-link-op $n0 $n2 orient right-down
$ns queue-limit $n0 $n2 5
$ns duplex-link $n1 $n2 1Mb 20ms DropTail
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link $n2 $n3 1Mb 20ms DropTail
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link $n3 $n4 1Mb 20ms DropTail

33
EC3401- Networks and Security Department of ECE 2022 - 2023

$ns duplex-link-op $n3 $n4 orient right-up


$ns duplex-link $n3 $n5 1Mb 20ms DropTail
$ns duplex-link-op $n3 $n5 orient right-down
Agent/TCP set_nam_tracevar_true
set tcp [new Agent/TCP]
$tcp set fid 1
$ns attach-agent $n1 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n4 $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns at 0.05 "$ftp start"
$ns at 0.06 "$tcp set windowlnit 6"
$ns at 0.06 "$tcp set maxcwnd 6"
$ns at 0.25 "$ns queue-limit $n3 $n4 0"
$ns at 0.26 "$ns queue-limit $n3 $n4 10"
$ns at 0.305 "$tcp set windowlnit 4"
$ns at 0.305 "$tcp set maxcwnd 4"
$ns at 0.368 "$ns detach-agent $n1 $tcp ; $ns detach-agent $n4 $sink"
$ns at 1.5 "finish"
$ns at 0.0 "$ns trace-annotate \"Goback N end\""
$ns at 0.05 "$ns trace-annotate \"FTP starts at 0.01\""
$ns at 0.06 "$ns trace-annotate \"Send 6Packets from SYS1 to SYS4\""
$ns at 0.26 "$ns trace-annotate \"Error Occurs for 4th packet so not sent ack for the Packet\""
$ns at 0.30 "$ns trace-annotate \"Retransmit Packet_4 to 6\""
$ns at 1.0 "$ns trace-annotate \"FTP stops\""
proc finish {} {
global ns nf
$ns flush-trace
close $nf
puts "filtering..."
#exec tclsh../bin/namfilter.tcl goback.nam
#puts "running nam..."
exec nam goback.nam &
exit 0
}
$ns run

OUTPUT:

RESULT:

34
EC3401- Networks and Security Department of ECE 2022 - 2023

EX.NO: Date:
SIMULATION OF SELECTIVE REPEAT
PROTOCOLS

AIM: Implementation and study of Go Back N and Selective repeat protocols


SOFTWARE REQUIREMENTS: NS-2 Simulator
THEORY: Selective Repeat ARQ is a specific instance of the Automatic Repeat-reQuest (ARQ)
Protocol. It may be used as a protocol for the delivery and acknowledgement of message units, or it
may be used as a protocol for the delivery of subdivided message sub-units. When used as the
protocol for the delivery of messages, the sending process continues to send a number of frames
specified by a window size even after a frame loss. Unlike Go-Back-N ARQ, the receiving process
will continue to accept and acknowledge frames sent after an initial error. The receiver process keeps
track of the sequence number of the earliest frame it has not received, and sends that number with
every ACK it sends. If a frame from the sender does not reach the receiver, the sender continues to
send subsequent frames until it has emptied its window. The receiver continues to fill its receiving
window with the subsequent frames, replying each time with an ACK containing the sequence
number of the earliest missing frame. Once the sender has sent all the frames in its window, it re-
sends the frame number given by the ACKs, and then continues where it left off. The size of the
sending and receiving windows must be equal, and half the maximum sequence number (assuming
that sequence numbers are numbered from 0 to n-1) to avoid miscommunication in all cases of
packets being dropped. To understand this, consider the case when all ACKs are destroyed. If the
receiving window is larger than half the maximum sequence number, some, possibly even all, of the
packages that are resent after timeouts are duplicates that are not recognized as such. The sender
moves its window for every packet that is acknowledged.
Advantage over Go Back N:
1. Fewer retransmissions.
Disadvantages:
1. More complexity at sender and receiver
2. Receiver may receive frames out of sequence
ALGORITHM: SELECTIVE REPEAT
1. The source node transmits the frames continuously.
2. Each frame in the buffer has a sequence number starting from 1 and increasing up to the window
size.
3. The source node has a window i.e. a buffer to store the frames. This buffer size is the number of
frames to be transmitted continuously.
4. The receiver has a buffer to store the received frames. The size of the buffer depends upon the
window size defined by the protocol designer.
5. The size of the window depends according to the protocol designer.
6. The source node transmits frames continuously till the window size is exhausted. If any of the
frames are received with error only those frames are requested for retransmission (with a negative
acknowledgement)
7. If all the frames are received without error, a cumulative positive acknowledgement is sent.

35
EC3401- Networks and Security Department of ECE 2022 - 2023

8. If acknowledgment is transmitted with error, all the frames of window are retransmitted. Else
ordinary window sliding takes place. (* In implementation part, Acknowledgment error is not
considered)
9. If all the frames transmitted are errorless the next transmission is carried out for the new window.
10. This concept of repeating the transmission for the error frames only is called Selective Repeat
transmission flow control protocol.
11. If there is an error in frame 3, an acknowledgement for the frame 2 is sent and then only Frame 3
is retransmitted. Now the window slides to get the next frames to the window.
12. If acknowledgment is transmitted with error, all the frames of window are retransmitted. Else
ordinary window sliding takes place. (* In implementation part, Acknowledgment error is not
considered)
13. If all the frames transmitted are errorless the next transmission is carried out for the new window.
15. This concept of repeating the transmission for the error frames only is called Selective Repeat
transmission flow control protocol.
#PROGRAM FOR SELECTIVE REPEAT:
#send packets one by one
set ns [new Simulator]
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 color "red"
$n1 color "red"
$n2 color "green"
$n3 color "green"
$n4 color "black"
$n5 color "black"
$n0 shape circle ;
$n1 shape circle ;
$n2 shape circle ;
$n3 shape circle ;
$n4 shape circle ;
$n5 shape circle ;
$ns at 0.0 "$n0 label SYS1"
$ns at 0.0 "$n1 label SYS2"
$ns at 0.0 "$n2 label SYS3"
$ns at 0.0 "$n3 label SYS4"
$ns at 0.0 "$n4 label SYS5"
$ns at 0.0 "$n5 label SYS6"
set nf [open Srepeat.nam w]
$ns namtrace-all $nf
set f [open Srepeat.tr w]

36
EC3401- Networks and Security Department of ECE 2022 - 2023

$ns trace-all $f
$ns duplex-link $n0 $n2 1Mb 10ms DropTail
$ns duplex-link-op $n0 $n2 orient right-down
$ns queue-limit $n0 $n2 5
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link $n2 $n3 1Mb 10ms DropTail
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link $n3 $n4 1Mb 10ms DropTail
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link $n3 $n5 1Mb 10ms DropTail
$ns duplex-link-op $n3 $n5 orient right-down
Agent/TCP set_nam_tracevar_true
set tcp [new Agent/TCP]
$tcp set fid 1
$ns attach-agent $n1 $tcp
set sink [new Agent/TCPSink]
$ns attach-agent $n4 $sink
$ns connect $tcp $sink
set ftp [new Application/FTP]
$ftp attach-agent $tcp
$ns at 0.05 "$ftp start"
$ns at 0.06 "$tcp set windowlnit 8"
$ns at 0.06 "$tcp set maxcwnd 8"
$ns at 0.25 "$ns queue-limit $n3 $n4 0"
$ns at 0.26 "$ns queue-limit $n3 $n4 10"
$ns at 0.30 "$tcp set windowlnit 1"
$ns at 0.30 "$tcp set maxcwnd 1"
$ns at 0.30 "$ns queue-limit $n3 $n4 10"
$ns at 0.47 "$ns detach-agent $n1 $tcp;$ns detach-agent $n4 $sink"
$ns at 1.75 "finish"
$ns at 0.0 "$ns trace-annotate \"Select and repeat\""
$ns at 0.05 "$ns trace-annotate \"FTP starts at 0.01\""
$ns at 0.06 "$ns trace-annotate \"Send 8Packets from SYS1 to SYS4\""
$ns at 0.26 "$ns trace-annotate \"Error Occurs in 4th packet \""
$ns at 0.30 "$ns trace-annotate \"Retransmit Packet_4 from SYS1 to SYS4\""
$ns at 1.5 "$ns trace-annotate \"FTP stops\""
proc finish {} {
global ns nf
$ns flush-trace
close $nf
puts "filtering..."
#exec tclsh../bin/namfilter.tcl srepeat.nam
#puts "running nam..."
exec nam Srepeat.nam &
exit 0
}
$ns run
OUTPUT:

RESULT:
REVIEW QUESTIONS
1. What do you mean by Selective Repeat flow Control?
2. What is size of the send and receive window in Selective repeat protocol?

37
EC3401- Networks and Security Department of ECE 2022 - 2023

3. What is the advantage of Selective repeat over Go back N protocol?


4. Define ARQ.
5. What are the disadvantages of Selective Repeat flow Control?
EX. NO: 6 Date:
IMPLEMENTATION OF DISTANCE VECTOR ROUTING
ALGORITHM
AIM:
To simulate distance vector routing algorithm using ns2.

REQUIREMENTS:

 NS-2.28
 Computer with windows XP

ALGORITHM:
Step 1: Start the program
Step 2: Create the trace file and NAM file.
Step 3: Setup the topology object
Step 4: Create nodes and set duplex links between the nodes.
Step 5: Create nodes and attach them to the queue, DROPTAIL
Step 6: Configure the nodes and provides initial location of nodes. Generation of movements
is done.
Step 7: Setup a TCP Connection between nodes
Step 8: Define a initialize positions for the nam window.
Step 9: Telling nodes when the simulation ends
Step 10: Ending nam and the simulation

PROGRAM:
Distance vector

38
EC3401- Networks and Security Department of ECE 2022 - 2023

OUTPUT:

RESULT:

39
EC3401- Networks and Security Department of ECE 2022 - 2023

EX. NO: 9
Date:
IMPLEMENT AND REALIZE THE NETWORK TOPOLOGY
STAR, BUS AND RING USING NS2.

AIM:
To implement and realize the network topologies.
REQUIREMENTS:
 NS-2.28
 Computer with windows XP
ALGORITHM:
Step 1: Start the program
Step 2: Create the trace file and NAM file.
Step 3: Setup the topology object
Step 4: Create nodes and set duplex links between the nodes.
Step 5: Create nodes and attach them to the queue, DROPTAIL
Step 6: Configure the nodes and provides initial location of nodes. Generation of movements
is done.
Step 7: Setup a TCP Connection between nodes
Step 8: Define a initialize positions for the nam window.
Step 9: Telling nodes when the simulation ends
Step 10: Ending nam and the simulation
#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 &
exit0
}
#Create four 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]
#Change the shape of center node in a star topology
$n0 shape square

#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 $n0 $n4 1Mb 10ms DropTail
$ns duplex-link $n0 $n5 1Mb 10ms DropTail
#Create a TCP agent and attach it to node n0
set tcp0 [new Agent/TCP]
$tcp0 set class_ 1

40
EC3401- Networks and Security Department of ECE 2022 - 2023

$ns attach-agent $n1 $tcp0


#Create a TCP Sink agent (a traffic sink) for TCP and attach it to node n3
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 for the CBR agents
$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"
#Call the finish procedure after 5 seconds of simulation time
$ns at 5.0 "finish"
#Run the simulation
$ns run

BUS TOPOLOGY:
#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

41
EC3401- Networks and Security Department of ECE 2022 - 2023

$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

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”

42
EC3401- Networks and Security Department of ECE 2022 - 2023

RESULT:

REVIEW QUESTIONS:
1. What is menat by topology
2. Define Ring topology
3. Define Star topology
4. Define Bus topology
5. Which is the suitable topology for real time network.

43

You might also like