EC8563 Comm Networks Lab Manual

You might also like

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

EXP NO:1

IMPLEMENTATION OF ERROR DETECTION AND


DATE:
CORRECTION TECHNIQUES

AIM:

To create a java program for implementing error correction and detection techniques
using Hamming codes.

ALGORITHM:

Step 1: Start the program.

Step 2: Get the message bits from the user.

Step 3: Calculate the number of parity bits to be added with the message.

Step 4: Generate the parity bits.

Step 5: Generate the Hamming code by adding the parity bits along with message in
respective location.

Step 6: Make a one bit error in transmitting Hamming code.

Step 7: Check the correctness of Hamming code and find the location of error if present
in received hamming code.

Step 8: Stop the program.


PROGRAM:

/* Implementation Of Error Detection And Correction Techniques*/

import java.util.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.*;
class HammingCode
{
public static void main(String args[])
{
Scanner scr=new Scanner(System.in);
System.out.println("This is Hamming code error detection & correction using even
parit");
System.out.println();
System.out.println("Enter 4 data bits D4 D3 D2 D1");
int n=4;
int d[]=new int[4];
for(int i=n-1;i>=0;--i)
{
System.out.println("enter the value of D"+(i+1));
d[i]=scr.nextInt();
}
int k=0;
while(Math.pow(2,k)<(n+k+1))
{
++k;
}
System.out.println();
System.out.println(k+"parity bits are required for the transmission of data bits");
int p[]=new int[k];
int h[]=new int[n+k+1];
for(int i=0;i<7;++i)
h[i]=-1;
int count=0;
int c=2;
while(count<4)
{
++c;
if(c==4)
continue;
h[c]=d[count];
++count;
}
int p1[]={h[1],h[3],h[5],h[7]};
int p2[]={h[2],h[3],h[6],h[7]};
int p3[]={h[4],h[5],h[6],h[7]};
int parity[]=new int[3];
parity[0]=set_parity_bit(p1);
parity[1]=set_parity_bit(p2);
parity[2]=set_parity_bit(p3);
h[1]=parity[0];
h[2]=parity[1];
h[4]=parity[2];
System.out.println("\nsender:");
System.out.print("\nThe data bits entered are:");
for(int i=3;i>=0;--i)
System.out.print(d[i]+"");
System.out.println("The parity bits are:");
for(int i=2;i>=0;--i)
System.out.println("value of p"+(i+1)+"is"+parity[i]+" ");
System.out.print("\nThe Hamming code is as follows:\nD4 D3 D2 P3 D1 P2
P1\n");
for(int i=(n+k);i>0;--i)
System.out.print(h[i]+" ");
System.out.println();
System.out.println();
System.out.println("Enter the hamming code with error at any position of your
choice");
for(int i=7;i>0;--i)
h[i]=scr.nextInt();
int p4[]={h[1],h[3],h[5],h[7]};
int p5[]={h[2],h[3],h[6],h[7]};
int p6[]={h[4],h[5],h[6],h[7]};
parity[0]=set_parity_bit(p4);
parity[1]=set_parity_bit(p5);
parity[2]=set_parity_bit(p6);
int
position=(int)(parity[2]*Math.pow(2,2)+parity[1]*Math.pow(2,1)+parity[0]*Math.pow(2,0));
System.out.println("Receiver");
System.out.println("Error is detected at position"+position+"at the receiver end");
System.out.println("Correcting the error");
if(h[position]==1)
h[position]=0;
else
h[position]=1;
System.out.print("The correct code is");
for(int i=7;i>0;--i)
System.out.print(h[i]+" ");
}
static int set_parity_bit(int a[])
{
int count=0;
int l=a.length;
for(int i=0;i<l;++i)
if(a[i]==1)
++count;
if((count%2)==0)
return 0;
else
return 1;
}}
OUTPUT:

E:\ece>java HammingCode
This is hamming code error detection and correction using EVEN parity

Enter 4 data bits.D4 D3 D2 D1


Enter the value of D4
1
Enter the value of D3
0
Enter the value of D2
0
Enter the value of D1
0

3 parity bits are required for the transmission of data bits.

SENDER:
The data bits entered are: 1 0 0 0
The Parity bits are:
Value of P3 is 1
Value of P2 is 1
Value of P1 is 1

The Hamming code is as follows :-


D4 D3 D2 P3 D1 P2 P1
1001011

Enter the hamming code with error at any position of your choice.
1
0
0
0
0
1
1

RECEIVER:
Error is detected at position 4 at the receiving end.
Correcting the error....
The correct code is 1 0 0 1 0 1 1

RESULT:

Thus the error correction & detection is successfully done & executed.
EXP NO: 2a
IMPLEMENTATION OF STOP AND WAIT PROTOCOL
DATE:

AIM:

To write a program in C to simulate the Stop & Wait Protocol.

STOP & WAIT:

A reliable transmission algorithm in which the sender transmits a packet and waits
for an acknowledgment before sending the next packet.

ALGORITHM:
SERVER:
Step 1:Start the Program
Step 2: Create the socket.
Step 3:Create the frame structure.
Step 4:Bind & connect with the socket.
Step 5:Receive the frame from the client.
Step 6:Send the acknowledgement to the client.
Step 7:If the frame is not received report to the client that the frame is not received.
Step 8.Repeat the above steps until all the frames are received.
Step 9.Stop the Program.

CLIENT:
Step 1:Start the program.
Step 2:Connect with the socket.
Step 3:Send the frame to the server.
Step 4:Send the next after receiving the acknowledgement from the server.
Step 5:If the acknowledgement is not received resend the frame again.
Step 6:If the frame is also lost resend the frame which is lost.
Step 7:Stop the program.
PROGRAM:
/* Implementation of Stop and Wait Protocol */

SERVER:

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class sender {


public static void main(String args[])
{
int p=9000,i,q=8000;
String h="localhost";
try
{
Scanner scanner = new Scanner(System.in);
System.out.print("Enter number of frames : ");
int number = scanner.nextInt();
if(number==0)
{
System.out.println("No frame is sent");
}
else
{
Socket s2;
s2= new Socket(h,q);
DataOutputStream d1 = new DataOutputStream(s2.getOutputStream());
d1.write(number);
}
String str1;
for (i=0;i<number;i++)
{
System.out.print("Enter message : ");
String name = scanner.next();
System.out.println("Frame " + i+" is sent");
Socket s1;
s1= new Socket(h,p+i);
DataOutputStream d = new DataOutputStream(s1.getOutputStream());
d.writeUTF(name);
DataInputStream dd= new DataInputStream(s1.getInputStream());
Integer sss1 = dd.read();
System.out.println("Ack for :" + sss1 + " is received");
}
}
catch(Exception ex)
{
System.out.println("ERROR :"+ex);
}
}
}

CLIENT:

import java.io.*;
import java.net.*;
import java.util.*;

public class receiver {


public static void main(String args[])
{
String h="Serverhost";
int q=5000;
int i;
try
{
ServerSocket ss2;
ss2 = new ServerSocket(8000);
Socket s1 =ss2.accept();
DataInputStream dd1= new DataInputStream(s1.getInputStream());
Integer i1 =dd1.read();
for(i=0;i<i1;i++)
{
ServerSocket ss1;
ss1 = new ServerSocket(9000+i);
Socket s =ss1.accept();
DataInputStream dd= new DataInputStream(s.getInputStream());
String sss1 = dd.readUTF();
System.out.println(sss1);
System.out.println("Frame "+ i+" received");
DataOutputStream d1 = new DataOutputStream(s.getOutputStream());
d1.write(i);
System.out.println("ACK sent for "+ i);
}
}
catch(Exception ex)
{
System.out.println("Error"+ex);
}
}
}

OUTPUT:

Server

Client

RESULT:
Thus the stop &wait protocol is successfully done & executed.
EXP NO:2b
DATE: IMPLEMENTATION OF SLIDING WINDOW PROTOCOL

AIM:

To write a program in C to simulate the Sliding Window Protocol.

SLIDING WINDOW PROTOCOL:

An algorithm that allows the sender to transmit multiple packets (up to the size of
the window) before receiving an acknowledgment. Asacknowledgments are returned for
those packets in the window that were sent first, the window “slides” and more packets
may be sent. The sliding window algorithm combines reliable delivery with a high
throughput.

ALGORITHM:

SERVER:

Step 1: A TCP socket is created.

Step 2: An Internet socket address structure is filled in with the wildcard address
(INADDR_ANY) and the server‟s well-known port (PORT).

Step 3: The socket is converted into a listening socket by calling the listen function.

Step 4: The server blocks in the call to accept, waiting for the client connection to
complete.

Step 5:When the connection is established, the server reads the source file name (which is
to be transferred) from the client using readn.

Step 6: It receives the data from the client as it receives data simultaneously based on the
congestion window(assuming the window size is 3) to the client.

Step 7: Finally,the server send the acknowledgement to the client based on how many
packets it received.

Step 8.Stop.
CLIENT:

Step 1:A TCP socket is created.

Step 2: An Internet socket address structure is filled in with the server‟s IP address and
the same port number.

Step 3: The connect function establishes the connection with the server.

Step 4. The client sends the data to server based on the congestion window size.

Step 5. It then receives the acknowledgement from the server based on how many data it
sends.

Step 6.Stop.

PROGRAM:
/ * Sliding Window Protocol */

Slide Sender:
import java.io.*;
import java.net.*;
import java.util.*;

public class Slide_Sender


{
Socket sender;

ObjectOutputStream out;
ObjectInputStream in;

String pkt;
char data='a';

int SeqNum = 1, SWS = 5;


int LAR = 0, LFS = 0;
int NF;

Slide_Sender()
{
}

public void SendFrames()


{
if((SeqNum<=15)&&(SWS > (LFS - LAR)) )
{
try
{
NF = SWS - (LFS - LAR);
for(int i=0;i<NF;i++)
{
pkt = String.valueOf(SeqNum);
pkt = pkt.concat(" ");
pkt = pkt.concat(String.valueOf(data));
out.writeObject(pkt);
LFS = SeqNum;
System.out.println("Sent " + SeqNum + " " + data);

data++;
if(data=='f')
data='a';

SeqNum++;
out.flush();
}
}
catch(Exception e)
{}
}
}

public void run() throws IOException


{
sender = new Socket("localhost",1500);

out = new ObjectOutputStream(sender.getOutputStream());


in = new ObjectInputStream(sender.getInputStream());

while(LAR<15)
{
try
{
SendFrames();

String Ack = (String)in.readObject();


LAR = Integer.parseInt(Ack);
System.out.println("ack received : " + LAR);
}
catch(Exception e)
{
}
}

in.close();
out.close();
sender.close();
System.out.println("\nConnection Terminated.");
}

public static void main(String as[]) throws IOException


{
Slide_Sender s = new Slide_Sender();
s.run();
}
}

Slide Receiver
import java.io.*;
import java.net.*;
import java.util.*;

public class Slide_Receiver


{
ServerSocket reciever;
Socket conc = null;

ObjectOutputStream out;
ObjectInputStream in;

String ack, pkt, data="";


int delay ;

int SeqNum = 0, RWS = 5;


int LFR = 0;
int LAF = LFR+RWS;

Random rand = new Random();

Slide_Receiver()
{
}

public void run() throws IOException, InterruptedException


{
reciever = new ServerSocket(1500,10);
conc = reciever.accept();

if(conc!=null)
System.out.println("Connection established :");

out = new ObjectOutputStream(conc.getOutputStream());


in = new ObjectInputStream(conc.getInputStream());

while(LFR<15)
{
try
{
pkt = (String)in.readObject();
String []str = pkt.split("\\s");

ack = str[0];
data = str[1];

LFR = Integer.parseInt(ack);

if((SeqNum<=LFR)||(SeqNum>LAF))
{
System.out.println("\nMsg received : "+data);
delay = rand.nextInt(5);

if(delay<3 || LFR==15)
{
out.writeObject(ack);
out.flush();
System.out.println("sending ack " +ack);
SeqNum++;
}
else
System.out.println("Not sending ack");
}
else
{
out.writeObject(LFR);
out.flush();
System.out.println("resending ack " +LFR);
}
}
catch(Exception e)
{
}
}
in.close();
out.close();
reciever.close();
System.out.println("\nConnection Terminated.");
}
public static void main(String args[]) throws IOException, InterruptedException
{
Slide_Receiver R = new Slide_Receiver();
R.run();
}
}

OUTPUT:

Sender
Receiver

RESULT:

Thus the sliding window protocol is successfully done & executed using c.
EXP NO:3
IMPLEMENTATION AND STUDY OF GO BACK N &
Date:
SELECTIVE REPEAT PROTOCOLS

AIM:

To implement the concept for Go Back N protocol using java programming.

ALGORITHM:

STEP 1: Start the program.

STEP 2: Get the number of frames to be sent from the user.

STEP 3: Send a group of 4 frames before waiting for acknowledgment.

STEP 4: Receiver receives the frame as soon as it receives it send the


acknowledgement for that particular frame.

STEP 5: If receiver receives frame in out of order then it discards the frame and
sends the NACK for the expected frame.

STEP 6: Transmitter transmit all the frames starting from lost frame in sequential
order.

STEP 7: Stop the program.


PROGRAM:
// Implementation Of Go Back N Protocol

CLIENT:
import java.util.*;
import java.net.*;
import java.io.*;
public class gobackclient
{
public static void main(String args[])throws Exception
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the value of m :");
int m=Integer.parseInt(br.readLine());
int x=(int)((Math.pow(2,m))-1);
System.out.println("Enter the no of frames to be sent: ");
int count=Integer.parseInt(br.readLine());
int data[]=new int[count];
int h=0;
for(int i=0;i<count;i++)
{
System.out.print("Enter data for no "+h+" =>");
data[i]=Integer.parseInt(br.readLine());
h=(h+1)%x;
}
Socket client=new Socket("localhost",6262);
ObjectInputStream ois=new ObjectInputStream(client.getInputStream());
ObjectOutputStream oos=new ObjectOutputStream(client.getOutputStream());
System.out.println("Connected with server");
boolean flag=false;
GoBackNListener listener=new GoBackNListener(ois,x);
listener=new GoBackNListener(ois,x);
listener.t.start();
int strt=0;
h=0;
oos.writeObject(x);
do
{
int c=h;
for(int i=h;i<count;i++)
{
System.out.print("| "+c+" |");
c=(c+1)%x;
}
System.out.println();
System.out.println();
h=strt;
for(int i=strt;i<x;i++)
{
System.out.println("Sending frame : "+h);
h=(h+1)%x;
System.out.println();
oos.writeObject(i);
oos.writeObject(data[i]);
Thread.sleep(100);
}
listener.t.join(3500);
if(listener.reply!=x-1)
{
System.out.println("No reply from server in 3.5 seconds. Resending data from frame no
"+(listener.reply+1));
System.out.println();
strt=listener.reply+1;
flag=false;
}
else
{
System.out.println("All elements sent successfully. Exiting");
flag=true;
}
}while(flag);
oos.writeObject(-1);
}
}
class GoBackNListener implements Runnable
{
Thread t;
ObjectInputStream ois;
int reply,x;
GoBackNListener(ObjectInputStream o,int i)
{
t=new Thread(this);
ois=o;
reply=-2;
x=i;
}
@Override
public void run()
{
try
{
int temp=0;
while(reply!=-1)
{
reply=(Integer)ois.readObject();
if(reply!=-1&&reply!=temp+1)
reply=temp;
if(reply!=-1)
{
temp=reply;
System.out.println("acknowledgement of frame no "+(reply%x)+" received");
System.out.println();
}
}
reply=temp;
}
catch(Exception e)
{
System.out.println("Exception => "+e);
}}}

SERVER:

import java.util.*;
import java.io.*;
import java.net.*;
public class gobacknserver
{
public static void main(String args[])throws Exception
{
ServerSocket server=new ServerSocket(6262);
System.out.println("Server established");
Socket client=server.accept();
ObjectOutputStream oos=new ObjectOutputStream(client.getOutputStream());
ObjectInputStream ois=new ObjectInputStream(client.getInputStream());
System.out.println("Client is now connected");
int x=(Integer)ois.readObject();
int k=(Integer)ois.readObject();
int j=0;
int i=(Integer)ois.readObject();
boolean flag=true;
Random r=new Random(6);
int mod=r.nextInt(6);
while(mod==1||mod==0)
mod=r.nextInt(6);
while(true)
{
int c=k;
for(int h=0;h<=x;h++){
System.out.print(" | "+c+" | ");
c=(c+1)%x;
}
System.out.println();
System.out.println();
if(k==j)
{
System.out.println("Frames received not in correct order "+" \n"+" Expected frame: "+j+"
\n"+"Received frame no: "+k);
j++;
System.out.println();
}
if(j%mod==0&&flag)
{
System.out.println("Error found. Acknowledgement not sent");
flag=!flag;
j--;
}
else if(k==j-1)
{
oos.writeObject(k);
System.out.println("Acknowledgement sent");}
System.out.println();
if(j%mod==0)
flag=!flag;
k=(Integer)ois.readObject();
if(k==-1)
break;
i=(Integer)ois.readObject();}
System.out.println("Client finished sending data.Exiting");
oos.writeObject(-1);}}
OUTPUT:

CLIENT SIDE:
D:\3 ece>java gobackclient
Enter the value of m :
2
Enter the no of frames to be sent:
4
Enter data for no 0 =>1
Enter data for no 1 =>2
Enter data for no 2 =>3
Enter data for no 0 =>4
Connected with server
| 0 || 1 || 2 || 0 |

Sending frame : 0
acknowledgement of frame no 0 received
Sending frame : 1
Sending frame : 2

No reply from server in 3.5 seconds. Resending data from frame no 1


SERVER SIDE:
D:\3 ece>java gobacknserver
Server established
Client is now connected
|0| |1| |2| |0|

Frames received not in correct order


Expected frame: 0
Received frame no: 0

Acknowledgement sent
|1| |2| |0| |1|

Frames received not in correct order


Expected frame: 1
Received frame no: 1

Error found. Acknowledgement not sent


|2| |0| |1| |2|
Client finished sending data.Exiting….

RESULT:
Thus the concept of Go Back N protocol using java programming
was implemented and output was verified
EXP NO:4 IMPLEMENTATION OF HIGH LEVEL DATA LINK
DATE: CONTROL

AIM:

To write a java program to implement the concept of high level data link
control(bit stuffing).

ALGORITHM:

STEP 1:Start the program.

STEP 2:Get the binary message from the user.

STEP3:If the entered message is not in binary form display that ” Enter only binary
values”.

STEP 4:Perform bit stuffing insert zero after 5 consecutive ones Inorder to avoid
data considered as a flag sequence.

STEP 5: Insert the flag(01111110) before and after data to Indicates start and end of
frame.

STEP 6:Transmit to the receiver

STEP 7:Receiver extract data from the frame by removing flags.

STEP 8:Perform bit unstuffing (remove zero after 5 consecutive 1’s) and get the
original data
PROGRAM:
// Implementation Of High Level Data Link Control Protocol

import java.util.*;
public class SEFBS
{
public static void main(String[] args)
{
System.out.print("Enter the binary message");
Scanner sn=new Scanner(System.in);
String data=sn.nextLine();
String res=new String();
String out=new String();
int counter=0;
for(int i=0;i<data.length();i++)
{
if(data.charAt(i)!='1' && data.charAt(i)!='0')
{
System.out.println("Enter only binary values!!!");
return;
}
if(data.charAt(i)!='1')
{
counter++;
res=res+data.charAt(i);
}
else
{
res=res+data.charAt(i);
counter=0;
}
if(counter==5)
{
res=res+'0';
counter=0;
}
}
String Inc="01111110"+res+"01111110";
System.out.println("The message to be transfered: "+Inc);
System.out.println("Sending the Message.....");
counter=0;
for(int i=0;i<res.length();i++)
{
if(res.charAt(i)=='1')
{
counter++;
out=out+res.charAt(i);}
else
{
out=out+res.charAt(i);
counter=0;}
if(counter==5)
{
if((i+2)!=res.length())
out=out+res.charAt(i+2);
else
out=out+' ';
i=i+2;
counter=1;}}
System.out.println("Message Received........Successfully!!!");
System.out.println(" The Destuffed Message is: "+out);}}
OUTPUT:

D:\3 ece>java SEFBS

Enter the binary message


01110001

The message to be transfered: 011111100111000101111110

Sending the Message.....

Message Received........Successfully!!!

The Destuffed Message is: 01110001

RESULT:

Thus the java program to implement the concept of high level data link
control(bit stuffing) was written and output was verified
EXP NO:5
IMPLEMENTATION OF IP COMMANDS SUCH AS PING,
Date:
TRACEROUTE, NS LOOKUP

AIM:
To create a java program for implementing IP commands such as ping, traceroute,
ns lookup
ALGORITHM:

PING:
Step 1:Start the program.
Step 2:Create a process to run the ping command.
Step 3:Get the IP address of remote system.
Step 4:Run the ping process by giving remote system IP address.
Step 5:Check the response from the remote system for its reachability.
Step 6:Stop the program.
TRACEROUTE:
Step 1:Start the program.
Step 2:Create a process to run the traceroute command.
Step 3:Get the IP address of remote system.
Step 4:Run the traceroute process by giving remote system IP address.
Step 5:Check the response from the remote system for its reachability.
Step 6:Stop the program.
NS LOOKUP:
Step 1:Start the program.
Step 2:Create a process to run the ns lookup command.
Step 3:Get the IP address of remote system.
Step 4:Run the ns lookup process by giving remote system IP address.
Step 5:Check the response from the remote system for its reachability.
Step 6:Stop the program

PROGRAM:

PING:
#include<stdio.h>
#include <stdlib.h>
#include<time.h>
#include <unistd.h>
int a[20][20],q[20],visited[20],n,i,j,f=0,r=-1, hop[20], flag=0, target, ttl;
clock_t start_t, end_t;
double total_t;
void bfs(int v)
{
sleep(1);
for(i=1;i<=n;i++)
if(a[v][i] && !visited[i])
{ q[++r]=i;
hop[i]=hop[v]+1;
if(i==target && hop[i]<=ttl)
{ end_t=clock();
//total_t = (double)(end_t - start_t)/(CLOCKS_PER_SEC);
total_t = (double)(end_t - start_t);
total_t = total_t*2;
printf("Destination is reachable at %d hops, rtt = %f seconds" , hop[i],
total_t);
flag=1;
exit(1);
}
}
if(f<=r)
{
visited[q[f]]=1;
bfs(q[f++]);
}
}
int main()
{
int v;
printf("\n Enter the number of vertices:");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
q[i]=0;
visited[i]=0;
}
printf("\n Enter graph data in matrix form:\n");
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
scanf("%d",&a[i][j]);
printf("\n Enter the starting vertex:");
scanf("%d",&v);
printf("\n Enter the destination vertex:");
scanf("%d",&target);
printf("\n Enter the ttl:");
scanf("%d",&ttl);
hop[v]=0;
start_t = clock();
bfs(v);
if(flag==0)
printf(" Desination not reachable at %d hops", ttl);}

OUTPUT:

Enter the Numbers of Vertices: 3


Enter Graph Data in matrix form
021
102
110

Enter the Starting Vertex:1

Enter the Destination Vertex: 3

Enter the ttl: 5

Destination is reachable at 1 hops, rtt = 2.087912 seconds_

TRACEROUTE
import java.io.*;
import java.net.*;
import java.lang.*;

class Traceroute
{
public static void main(String args[]){

BufferedReader in;

try{
Runtime r = Runtime.getRuntime();
Process p = r.exec("tracert www.google.com");

in = new BufferedReader(new InputStreamReader(p.getInputStream()));

String line;

if(p==null)
System.out.println("could not connect");

while((line=in.readLine())!=null){

System.out.println(line);
//in.close();
}

}catch(IOException e){

System.out.println(e.toString());

}
}
}

OUTPUT TRACEROUTE
Tracing route to www.google.com [74.125.28.106]
over a maximum of 30 hops:

1 70 ms 55 ms 70 ms 10.228.129.13
2 87 ms 84 ms 10.228.149.14
3 82 ms 85 ms 116.202.226.145
4 95 ms 94 ms 136 ms 10.228.158.82
5 Request timed out.
6 53 ms 55 ms 59 ms 116.202.226.21
7 85 ms 74 ms 82 ms 72.14.205.145
8 76 ms 75 ms 71 ms 72.14.235.69
9 124 ms 114 ms 113 ms 216.239.63.213
10 181 ms 194 ms 159 ms 66.249.95.132
11 285 ms 247 ms 246 ms 209.85.142.51
12 288 ms 282 ms 283 ms 72.14.233.138
13 271 ms 283 ms 274 ms 64.233.174.97
14 Request timed out.
15 269 ms 273 ms 283 ms pc-in-f106.1e100.net [74.125.28.106]

Trace complete.

NS LOOKUP
import java.net.*;
import java.io.*;
public class Program
{
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
if(args.length > 0 ){ //use command line
for(int i=0; i<args.length; i++){
System.out.println(lookup(args[i]));
}
}else{
BufferedReader in = new BufferedReader(new InputStreamReader (System.in));
System.out.println("Enter hostname or IP addresse.Enter \"exit\" to quit");
try{
while(true){
String host = in.readLine();
if(host.equalsIgnoreCase("exit")||host.equalsIgnoreCase("quit")){
break;
}
System.out.println(lookup(host));
}
}catch(IOException e){
System.err.println(e);
}
}
} /*end main */

private static String lookup(String host){


InetAddress node;
//get the bytes of the address
try{
node = InetAddress.getByName(host);

}catch(UnknownHostException e){
return "Cannot resolve host " + host;
}
if(isHostname(host)){
return node.getHostAddress();
}else {
//this is an IP address
return node.getHostName();
}
} // end of lookup

private static boolean isHostname(String host) {

//is this a ipv6 address


if(host.indexOf(":") != -1) return false;

char[] ca = host.toCharArray();
//if we see a character that is neither a digit nor a period
//then host is probably a hostname
for(int i=0; i<ca.length; i++){
if(!Character.isDigit(ca[i])){
if(ca[i] != '.') return true;
}
}
//Everything was either a digit or a period
// so host looks like a ip4v address in dotted quad format

return false;
}//end ishostname

}//end nslookupclone

OUT PUT NS LOOKUP

RESULT:

Thus the java program for implementing IP commands such as ping,


traceroute, ns lookup.
EXP NO:6 IMPLEMENTATION OF IP ADDRESS CONFIGURATION
DATA:

AIM :

To perform implementation of IP address Configuration.

ALGORITHM:

Step 1:Start the program.


Step 2:Create a process to run the IP address command.
Step 3:Get the IP address of remote system.
Step 4:Run the IP address process by giving remote system IP address.
Step 5:Check the response from the remote system for its reachability.
Step 6:Stop the program

PROGRAM

import java.net.*;
import java.io.*;
import java.util.*;
import java.net.InetAddress;

public class JavaProgram


{
public static void main(String args[]) throws Exception
{
// Returns the instance of InetAddress containing
// local host name and address
InetAddress localhost = InetAddress.getLocalHost();
System.out.println("System IP Address : " +
(localhost.getHostAddress()).trim());

// Find public IP address


String systemipaddress = "";
try
{
URL url_name = new URL("http://bot.whatismyipaddress.com");

BufferedReader sc =
new BufferedReader(new InputStreamReader(url_name.openStream()));

// reads system IPAddress


systemipaddress = sc.readLine().trim();
}
catch (Exception e)
{
systemipaddress = "Cannot Execute Properly";
}
System.out.println("Public IP Address: " + systemipaddress +"\n");
}
}

OUTPUT

System IP Address : 10.0.8.204


Public IP Address : 35.166.48.97

RESULT:

Thus the java program for implementing IP Address Configuration Output Is


Successfully Verified
EXP NO:7 TO CREATE SCENARIO AND STUDY THE PERFORMANCE OF
NETWORK WITH CSMA/CA & COMPARE WITH CSMA/CD
DATA: PROTOCOLS

AIM: To create scenario and study the performance of CSMA / CD protocol through simulation.

SOFTWARE REQUIREMENTS: Ns-2

THEORY: Ethernet is a LAN (Local area Network) protocol operating at the MAC (Medium
Access Control) layer. Ethernet has been standardized as per IEEE 802.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. If the channel is
busy then, the station defers transmission until the channel is sensed to be idle and then
immediately transmitted. If more than one node starts data transmission at the same time, the
data collides. This collision is heard by the transmitting nodes which enter into contention phase.
The contending nodes resolve contention using an algorithm called Truncated binary exponential
back off.

ALGORITHM:
1. Create a simulator object
2. Define different colors for different data flows
3. Open a nam trace file and define finish procedure then close the trace file, and execute nam
on trace file.
4. Create six nodes that forms a network numbered from 0 to 5
5. Create duplex links between the nodes and add Orientation to the nodes for setting a LAN
topology
6. Setup TCP Connection between n(0) and n(4)
7. Apply FTP Traffic over TCP
8. Setup UDP Connection between n(1) and n(5)
9. Apply CBR Traffic over UDP.
10. Apply CSMA/CA and CSMA/CD mechanisms and study their performance
11. Schedule events and run the program.

PROGRAM:
CSMA/CA 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/Ca 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] $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:

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] $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 study of analysis of csma/ca and csma/cd protocols output is verified
EXP NO:8 NETWORK TOPOLOGY - STAR, BUS AND RING
DATA:

AIM:

To write a ns2 program for implementing network topology.

ALGORITHM:

Step 1: start the program.


Step 2: declare the global variables ns for creating a new simulator.
Step 3: set the color for packets.
Step 4: open the network animator file in the name of file2 in the write mode.
Step 5: open the trace file in the name of file 1 in the write mode.
Step 6: set the unicast routing protocol to transfer the packets in network.
Step 7: create the required no of nodes.
Step 8: create the duplex-link between the nodes based on topology.
Step 9: give the position for the links between the nodes.
Step 10: set a tcp reno connection for source node.
Step 11: set the destination node using tcp sink.
Step 12: setup a ftp connection over the tcp connection.
Step 13: down the connection between any nodes at a particular time.
Step 14: reconnect the downed connection at a particular time.
Step 15: define the finish procedure.
Step 16: in the definition of the finish procedure declare the global variables
ns,file1,file2.
Step 17: close the trace file and namefile and execute the network animation file.
Step 18: at the particular time call the finish procedure.
Step 19: stop the program.
PROGRAM:
//Implementation Of Network Topology Star, Bus, Ring

BUS 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]
set n4 [$ns node]

#CreateLanbetween the nodes


set lan0 [$ns newLan "$n0 $n1 $n2 $n3 $n4" 0.5Mb 40ms LL Qu
eue/DropTail MAC/Csma/Cd Channel]

#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 (a traffic sink) for TCP and attac
h 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 ti


me
$ns at 5.0 "finish"

#Run the simulation


$ns run

RING TOPOLOGY
#**********************************************************
*************#
#Aim : To monitor traffic for Ring topology using NS2
#**********************************************************
*************#

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

#Create links between the nodes


$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

#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 (a traffic sink) for TCP and attac
h 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 ti


me
$ns at 5.0 "finish"

#Run the simulation


$ns run
OUTPUT:

RING Topology:

RESULT:

Thus the ns2 program to implement the network topology was written and the
output was verified.
EXP NO:9
IMPLEMENTATION OF DISTANCE VECTOR ROUTING
DATE: ALGORITHM

AIM:

To implement the concept of distance vector routing using C.

DISTANCE VECTOR ROUTING:

Distance Vector Routing is one of the routing algorithms used in a Wide


Area Network for computing shortest path between source and destination. The router is one of
the main devices used in a wide area network.The main task of the router is routing.It forms
the routing table and delivers the packets depending upon the routes in the table–either directly
or via an intermediate device(perhaps another router).
Each router initially has information about its all neighbors (i.e., it is directly
connected). After a period of time, each router exchanges its routing table among its
neighbors. After certain number of exchanges, all routers will have the full routing information
about the area of the network.
After each table exchange, router re computes the shortest path between the routers.
The algorithm used for this routing is called Distance Vector Routing.

ALGORITHM:
• Repeat the following steps until there is no change in the routing table for all routers.
1.Take the Next Router routing table and its neighbor routing table

2. Add the router entry that is not in your own routing table, but exists in any one of the other
routing tables. If the new router entry exists in more than one neighbor, then find the minimum
cost among them. The minimum cost value details are taken as a new entry: such as source
router, intermediate router, destination router and cost value, etc.

3. Update the source router routing table cost value if both the destination router and the
intermediate router field value have the same value as any one of the neighbors’ routing entry.

4.Update the source router’s routing table entry with the new advertised one if the
intermediate router value in the source table is not same, but the cost value is greater than the its
neighbor’s entry.

5.Write the next stage of routing table into the file. Repeat steps 1 to 5 for all routers.

6.Check whether any changes are made in any of the routers. If yes, then repeat the above
steps, otherwise, quit the process
PROGRAM:
// Implementation Of Distance Vector Routing

#include<stdio.h>
struct node
{
unsigned dist[20];
unsigned from[20];
}rt[10];
int main()
{
int dmat[20][20];
int n,i,j,k,count=0;
printf("\nEnter the number of nodes : ");
scanf("%d",&n);
printf("\nEnter the cost matrix :\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
scanf("%d",&dmat[i][j]);
dmat[i][i]=0;
rt[i].dist[j]=dmat[i][j];
rt[i].from[j]=j;
do
{
count=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
for(k=0;k<n;k++)
if(rt[i].dist[j]>dmat[i][k]+rt[k].dist[j])
{
rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];
rt[i].from[j]=k;
count++;
}
}while(count!=0);
for(i=0;i<n;i++)
{
printf("\n\nState value for router %d is \n",i+1);
for(j=0;j<n;j++)
{
printf("\t\nnode %d via %d Distance %d",j+1,rt
[i].from[j]+1,rt[i].dist[j]);
}}
printf("\n\n");}
OUTPUT:

Enter the number of nodes : 4

Enter the cost matrix :


0 3 5 99
3 0 99 1
5 4 0 2
99 1 2 0

State value for router 1 is


node 1 via 1 Distance0
node 2 via 2 Distance3
node 3 via 3 Distance5
node 4 via 2 Distance4

State value for router 2 is


node 1 via 1 Distance3
node 2 via 2 Distance0
node 3 via 4 Distance3
node 4 via 4 Distance1

State value for router 3 is


node 1 via 1 Distance5
node 2 via 4 Distance3
node 3 via 3 Distance0
node 4 via 4 Distance2

State value for router 4 is


node 1 via 2 Distance4
node 2 via 2 Distance1
node 3 via 3 Distance2
node 4 via 4 Distance0

RESULT:
Thus the concept of Distance Vector Routing was implemented successfully
and the output was verified.
EXP NO:10
IMPLEMENTATION OF LINK STATE ROUTING ALGORITHM
DATE:

AIM:

To implement the concept Link state routing Algorithm using C

INTRODUCTION:
The router is one of the main devices used in a wide area network. The
main task of the router is routing. It forms the routing table and delivers the
packets depending upon the routes in the table – either directly or via
an intermediate device (perhaps another router).Link state algorithm is a
method used to find the shortest path between a source router and a
destination router based on the distance and route the packets through that
route.

ALGORITHM:

1. Start with the router: the root of the tree

2. Assign a cost of 0 to this router and make it the first permanent router.

3. Examine each neighbor router of the router that was the last permanent
router.

4. Assign a cumulative cost to each router and make it temporary.

5. Among the list of temporary routers

5. a. Find the router with the smallest cumulative cost and make it
permanent.

5. b. If a router can be reached from more than one direction

5. b.1. Select the direction with the shortest cumulative

6. Repeat steps 3 to 5 until every router becomes permanent. Description


PROGRAM:
// Implementation Of Link State Routing Algorithm

#include<stdio.h>
main()
{
int n,a[10][10],i,j,k;
printf("\n ENTER THE NO.OF NODES: ");
scanf("%d",&n);
printf("\n ENTER THE <span id="IL_AD4" class="IL_AD">MATRIX</span>
ELEMENTS: ");
for(i=0;i<n;i++)
{
printf("\nENTER THE <span id="IL_AD5" class="IL_AD">DISTANCE</span> FOR
NODE:%d\n",i+1);
for(j=0;j<n;j++)
{
scanf("%d",&a[i][j]);
}
}
for(i=0;i<n;i++)
{
printf("<span id="IL_AD2" class="IL_AD">THE LINK</span> STATE PACKETS FOR
NODE:%d\n",i+1);
printf("\n NODE\tDISTANCE\n");
for(j=0;j<n;j++)
{
if(a[i][j]!=0&&a[i][j]!=-1)
{
printf("%d\t%d\n",j+1,a[i][j]);
}
}
printf("\n\n");
}
}
OUTPUT:

RESULT:

Thus the concept of Link State Routing was implemented and output was verified
EXP NO.11 STUDY OF NETWORK SIMULATOR (NS) AND
DATE: SIMULATION OF CONGESTION CONTROL ALGORITHMS
USING NS

AIM:

To Study of Network simulator (NS).and Simulation of Congestion Control


Algorithms using NS2.

NET WORK SIMULATOR (NS2)


Ns overview

Ns programming: A Quick start


Case study I: A simple Wireless network
Case study II: Create a new agent in Ns

Ns overview

Ns Status
Periodical release (ns-2.26, Feb 2003)
Platform support
FreeBSD, Linux, Solaris, Windows and Mac

Ns functionalities

Routing, Transportation, Traffic sources, Queuing,


disciplines, QoS

Wireless

Ad hoc routing, mobile IP, sensor-MAC Tracing, visualization and various utilities
NS(Network Simulators)

Most of the commercial simulators are GUI driven, while some network simulators
are CLI driven. The network model / configuration describes the state of the network
(nodes,routers, switches, links) and the events (data transmissions, packet error etc.). An
important output of simulations are the trace files. Trace files log every packet, every
event that occurred in the simulation and are used for analysis. Network simulators can
also provide other tools to facilitate visual analysis of trends and potential trouble spots.
Most network simulators use discrete event simulation, in which a list of pending
"events" is stored, and those events are processed in order, with some events triggering
future events—such as the event of the arrival of a packet at one node triggering the event
of the arrival of that packet at a downstream node.
Simulation of networks is a very complex task. For example, if congestion is high,
then estimation of the average occupancy is challenging because of high variance. To
estimate the likelihood of a buffer overflow in a network, the time required for an
accurate answer can be extremely large. Specialized techniques such as "control variates"
and "importance sampling" have been developed to speed simulation.

Examples of network simulators

There are many both free/open-source and proprietary network simulators.


Examples of notable network simulation software are, ordered after how often they are
mentioned in research papers:

1. ns (open source)
2. OPNET (proprietary software)
3. NetSim (proprietary software)

Uses of network simulators

Network simulators serve a variety of needs. Compared to the cost and time
involved in setting up an entire test bed containing multiple networked computers, routers
and data links, network simulators are relatively fast and inexpensive. They allow
engineers, researchers to test scenarios that might be particularly difficult or expensive to
emulate using real hardware - for instance, simulating a scenario with several nodes or
experimenting with a new protocol in the network. Network simulators are particularly
useful in allowing researchers to test new networking protocols or changes to existing
protocols in a controlled and reproducible environment. A typical network simulator
encompasses a wide range of networking technologies and can help the users to build
complex networks from basic building blocks such as a variety of nodes and links. With
the help of simulators, one can design hierarchical networks using various types of nodes
like computers, hubs, bridges, routers, switches, links, mobile units etc.

Various types of Wide Area Network (WAN) technologies like TCP, ATM, IP etc.
and Local Area Network (LAN) technologies like Ethernet, token rings etc., can all be
simulated with a typical simulator and the user can test, analyze various standard results
apart from devising some novel protocol or strategy for routing etc. Network simulators
are also widely used to simulate battlefield networks in Network-centric warfare

Packet loss

Occurs when one or more packets of data traveling across a computer network fail
to reach their destination. Packet loss is distinguished as one of the three main error types
encountered in digital communications; the other two being bit error and spurious packets
caused due to noise.
Packets can be lost in a network because they may be dropped when a queue in
the network node overflows. The amount of packet loss during the steady state is another
important property of a congestion control scheme. The larger the value of packet loss,
the more difficult it is for transport layer protocols to maintain high bandwidths, the
sensitivity to loss of individual packets, as well as to frequency and patterns of loss
among longer packet sequences is strongly dependent on the application itself.

Throughput

This is the main performance measure characteristic, and most widely used. In
communication networks, such as Ethernet or packet radio, throughput or network
throughput is the average rate of successful message delivery over a communication
channel. The throughput is usually measured in bits per second (bit/s or bps), and
sometimes in data packets per second or data packets per time slot This measure how
soon the receiver is able to get a certain amount of data send by the sender. It is
determined as the ratio of the total data received to the end to end delay. Throughput is an
important factor which directly impacts the network performance

Delay

Delay is the time elapsed while a packet travels from one point e.g., source
premise or network ingress to destination premise or network degrees. The larger the
value of delay, the more difficult it is for transport layer protocols to maintain high
bandwidths. We will calculate end to end delay

Queue Length

A queuing system in networks can be described as packets arriving for service,


waiting for service if it is not immediate, and if having waited for service, leaving the
system after being served. Thus queue length is very important characteristic to determine
that how well the active queue management of the congestion control algorithm has been
working.

RESULT:

Thus Network simulator (NS).and Simulation of Congestion Control


Algorithms using NS2 was studied.
EXP NO:12 IMPLEMENTATION OF ENCRYPTION AND
DATE: DECRYPTION ALGORITHMS USING ANY
PROGRAMMING LANGUAGE

AIM:

To implement the concept of Data encryption and decryption using netsim.

DATA ENCRYPTION AND DECRYPTION:

In encryption, each letter position in the file text which is given in encrypt
mode is changed according to the ascending order of the key text.
In decryption each letter position in the encrypted file text is changed
according to the ascending order of the key text.

ALGORITHM:

ENCRYPTION:

1. Get the text to be encrypted (plain text) and key text.


2. Find the length of the plain text.
3. For i=1 to length of plain text
Find the binary equivalent of ith character of plain text.
Find the binary equivalent of ith character of key text
Find the XOR of above two values.
4 . The resulting value will be the encrypted format (cipher text) of the
plain text

DECRYPTION:

1. Get the text to be decrypted (cipher text) and key text.


2. Fnd the length of the cipher text.
3. For i=1 to length of cipher text
Find the binary equivalent of ith character of cipher text.
Find the binary equivalent of ith character of key text
Find the XOR of above two values.
4. The resulting value will be the decrypted format (original plain text) of
the cipher plain text.
PROGRAM:
//Implementation Of Data Encryption And Decryption

import java.io.DataInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
public class RSA
{
private BigInteger p;
private BigInteger q;
private BigInteger N;
private BigInteger phi;
private BigInteger e;
private BigInteger d;
private int bitlength = 1024;
private Random r;
public RSA()
{
r = new Random();
p = BigInteger.probablePrime(bitlength, r);
q = BigInteger.probablePrime(bitlength, r);
N = p.multiply(q);
phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e = BigInteger.probablePrime(bitlength / 2, r);
while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) <
0)
{
e.add(BigInteger.ONE);
}
d = e.modInverse(phi);
}
public RSA(BigInteger e, BigInteger d, BigInteger N)
{
this.e = e;
this.d = d;
this.N = N;
}
@SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException
{
RSA rsa = new RSA();
DataInputStream in = new DataInputStream(System.in);
String teststring;
System.out.println("Enter the plain text:");
teststring = in.readLine();
System.out.println("Encrypting String: " + teststring);
System.out.println("String in Bytes: "
+ bytesToString(teststring.getBytes()));
// encrypt
byte[] encrypted = rsa.encrypt(teststring.getBytes());
// decrypt
byte[] decrypted = rsa.decrypt(encrypted);
System.out.println("Decrypting Bytes: " + bytesToString(decrypted));
System.out.println("Decrypted String: " + new String(decrypted));
}
private static String bytesToString(byte[] encrypted)
{
String test = "";
for (byte b : encrypted)
{
test += Byte.toString(b);
}
return test;
}
// Encrypt message
public byte[] encrypt(byte[] message)
{
return (new BigInteger(message)).modPow(e, N).toByteArray();
}
// Decrypt message
public byte[] decrypt(byte[] message)
{
return (new BigInteger(message)).modPow(d, N).toByteArray();
}
}
OUTPUT:

$ javac RSA.java

$ java RSA

Enter the plain text:Sanfoundry

Encrypting String: Sanfoundry

String in Bytes: 8397110102111117110100114121

Decrypting Bytes: 8397110102111117110100114121

Decrypted String: Sanfoundry

RESULT:

Thus the concept of Data encryption and decryption using netsim was
implemented and output was verified.

You might also like