Professional Documents
Culture Documents
EC8563 Comm Networks Lab Manual
EC8563 Comm Networks Lab Manual
EC8563 Comm Networks Lab Manual
AIM:
To create a java program for implementing error correction and detection techniques
using Hamming codes.
ALGORITHM:
Step 3: Calculate the number of parity bits to be added with the message.
Step 5: Generate the Hamming code by adding the parity bits along with message in
respective location.
Step 7: Check the correctness of Hamming code and find the location of error if present
in received hamming code.
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
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
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:
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;
CLIENT:
import java.io.*;
import java.net.*;
import java.util.*;
OUTPUT:
Server
Client
RESULT:
Thus the stop &wait protocol is successfully done & executed.
EXP NO:2b
DATE: IMPLEMENTATION OF SLIDING WINDOW PROTOCOL
AIM:
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 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 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.*;
ObjectOutputStream out;
ObjectInputStream in;
String pkt;
char data='a';
Slide_Sender()
{
}
data++;
if(data=='f')
data='a';
SeqNum++;
out.flush();
}
}
catch(Exception e)
{}
}
}
while(LAR<15)
{
try
{
SendFrames();
in.close();
out.close();
sender.close();
System.out.println("\nConnection Terminated.");
}
Slide Receiver
import java.io.*;
import java.net.*;
import java.util.*;
ObjectOutputStream out;
ObjectInputStream in;
Slide_Receiver()
{
}
if(conc!=null)
System.out.println("Connection established :");
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:
ALGORITHM:
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.
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
Acknowledgement sent
|1| |2| |0| |1|
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:
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 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:
Message Received........Successfully!!!
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:
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");
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 */
}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
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
RESULT:
AIM :
ALGORITHM:
PROGRAM
import java.net.*;
import java.io.*;
import java.util.*;
import java.net.InetAddress;
BufferedReader sc =
new BufferedReader(new InputStreamReader(url_name.openStream()));
OUTPUT
RESULT:
AIM: To create scenario and study the performance of CSMA / CD protocol through simulation.
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
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:
ALGORITHM:
BUS Topology:
#Create a simulator object
set ns [new Simulator]
RING TOPOLOGY
#**********************************************************
*************#
#Aim : To monitor traffic for Ring topology using NS2
#**********************************************************
*************#
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:
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:
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:
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:
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.
5. a. Find the router with the smallest cumulative cost and make it
permanent.
#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:
Ns overview
Ns Status
Periodical release (ns-2.26, Feb 2003)
Platform support
FreeBSD, Linux, Solaris, Windows and Mac
Ns functionalities
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.
1. ns (open source)
2. OPNET (proprietary software)
3. NetSim (proprietary software)
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
RESULT:
AIM:
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:
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
RESULT:
Thus the concept of Data encryption and decryption using netsim was
implemented and output was verified.