CNS Lab Programs-Updated
CNS Lab Programs-Updated
1. Implement three nodes point – to – point network with duplex links between them. Set the
queue size, vary the bandwidth, and find the number of packets dropped.
2. Implement transmission of ping messages/trace route over a network topology consisting of 6
nodes and find the number of packets dropped due to congestion.
3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot congestion
window for different source / destination.
4. Develop a program for error detecting code using CRC-CCITT (16- bits).
5. Develop a program to implement a sliding window protocol in the data link layer.
6. Develop a program to find the shortest path between vertices using the Bellman-Ford and path
vector routing algorithm.
7. Using TCP/IP sockets, write a client – server program to make the client send the file name
and to make the server send back the contents of the requested file if present.
8. Develop a program on a datagram socket for client/server to display the messages on client
side, typed at the server side.
9. Develop a program for a simple RSA algorithm to encrypt and decrypt the data.
10. Develop a program for congestion control using a leaky bucket algorithm.
Introduction to NS-2:
Tcl scripting
• Tcl is a general purpose scripting language. [Interpreter]
• Tcl runs on most of the platforms such as Unix, Windows, and Mac.
• The strength of Tcl is its simplicity.
• It is not necessary to declare a data type for variable prior to the usage.
Basics of TCL
➢ Hello World:
puts stdout{Hello, World!}
Hello, World!
➢ Variables: Command Substitution
proc Diag {a b} {
set c [expr sqrt($a * $a + $b * $b)]
return $c }
puts ―Diagonal of a 3, 4 right triangle is [Diag 3 4]‖
➢ Loops
Which is thus the first line in the tcl script? This line declares a new variable as using the set command, you can
call this variable as you wish, In general people declares it as ns because it is an instance of the Simulator class,
so an object the code[new Simulator] is indeed the installation of the class Simulator using the reserved word
new. In order to have output files with data on the simulation (trace files) or files used for visualization (nam
files), we need to create the files using ―open command:
#Open the Trace file
set tracefile1 [open out.tr w]
$ns trace-all $tracefile1
#Open the NAM trace file
set namfile [open out.nam w]
$ns namtrace-all $namfile
The above creates a dta trace file called ―out.tr and a nam visualization trace file called ―out.nam.
Within the tcl script, these files are not called explicitly by their names, but instead by pointers that are declared
above and called ―tracefile1 and ―namfile respectively. Remark that they begins with a # symbol.The second line
open the file ―out.tr‖ to be used for writing, declared with the letter ―w‖.The third line uses a simulator method
called trace-all that have as parameter the name of the file where the traces will go.
The last line tells the simulator to record all 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.In our case,this will be the file pointed at by the pointer
―$namfile‖,i.e the file ―out.tr‖.
The termination of the program is done using a ―finish procedure.
#Define a “finish” procedure
Proc finish { } {
global ns tracefile1 namfile
$ns flush-trace
Close $tracefile1
Close $namfile
Exec nam out.nam &
Exit 0
}
The word proc declares a procedure in this case called finish and without arguments. The word global is used to tell
that we are using variables declared outside the procedure. The simulator method ―flush-trace” will dump the traces
on the respective files. The tcl command ―close” closes the trace files defined before and exec executes the nam
program for visualization. The command exit will ends the application and return the number 0 as status to the
system. Zero is the default for a clean exit. Other values can be used to say that is a exit because something fails.
At the end of ns program we should call the procedure ―finish and specify at what time the termination should
occur. For example, $ns at 125.0 “finish” will be used to call ―finish‖ at time 125sec.Indeed,the at method of
the simulator allows us to schedule events explicitly.
The simulation can then begin using the command: $ns run
1. The first field is the event type. It is given by one of four possible symbols r, +, -, d which correspond respectively
to receive (at the output of the link), enqueued, dequeued and dropped.
2. The second field gives the time at which the event occurs.
3. Gives the input node of the link at which the event occurs.
4. Gives the output node of the link at which the event occurs.
5. Gives the packet type (eg CBR or TCP)
6. Gives the packet size
7. Some flags
8. This is the flow id (fid) of IPv6 that a user can set for each flow at the input OTcl script one can further use this
field for analysis purposes; it is also used when specifying stream color for the NAM display.
9. This is the source address given in the form of ―node.port‖.
10. This is the destination address, given in the same form.
11. This is the network layer protocol’s packet sequence number. Even though UDP implementations in a real
network do not use sequence number, ns keeps track of UDP packet sequence number for analysis purposes
12. The last field shows the Unique id of the packet.
Awk- An Advanced
awk is a programmable, pattern-matching, and processing tool available in UNIX. It works equally well with
text and numbers. awk is not just a command, but a programming language too. In other words, awk utility is a
pattern scanning and processing language. It searches one or more files to see if they contain lines that match
specified patterns and then perform associated actions, such as writing the line to the standard output or
incrementing a counter each time it finds a match.
Syntax:
awk option ‘selection criteria {action}’ file(s)
1. Implement three nodes point – to – point network with duplex links between them. Set
the queue size, vary the bandwidth and find the number of packets dropped.
File: lab1.tcl
#Create a new Simulation Instance
set ns [new Simulator]
$ns trace-all $f
$ns namtrace-all $nf
proc finish {} {
global f nf ns
$ns flush-trace
close $f
close $nf
exec nam out.nam &
exec awk -f 1.awk out.tr &
exit 0
}
File: lab1.awk
#!/usr/bin/awk -f
BEGIN{
cbrPkt=0;
tcpPkt=0;
}
{
if(($1 == "d")&&($5 == "cbr")) {
cbrPkt = cbrPkt + 1;
}
if(($1 == "d")&&($5 == "tcp")) {
tcpPkt = tcpPkt + 1;
}
}
END {
printf "\nNo. of CBR Packets Dropped %d", cbrPkt;
printf "\nNo. of TCP Packets Dropped %d", tcpPkt;
}
Steps for execution:
1. Open vi editor and type program.
2. Program name should have the extension “ .tcl ” vi lab1.tcl
Save the program by pressing ESC :wq and press enter
3. Open vi editor and type awk program. Program name should have the extension “.awk ” vi lab1.awk
Save the program by pressing ESC:wq and press Enter key.
4. Run the simulation program : ns lab1.tcl Here “ns” indicates network simulator. We get the topology shown
in the snapshot.
5. Now press the play button in the simulation window and the simulation will begins.
6.After simulation is completed run awk file to see the output:
awk –f lab1.awk lab1.tr
7. To see the trace file contents open the file as : vi lab1.tr
Output:
2. Implement transmission of ping messages/trace route over a network topology
consisting of 6 nodes and find the number of packets dropped due to congestion.
File : lab2.tcl
$ns trace-all $f
$ns namtrace-all $nf
proc finish {} {
global ns f nf
$ns flush-trace
close $f
close $nf
exec nam out.nam &
exit 0
}
proc sendPingPacket {} {
global ns ping0 ping1
set intervalTime 0.001
set now [$ns now]
$ns at [expr $now + $intervalTime] "$ping0 send"
$ns at [expr $now + $intervalTime] "$ping1 send"
$ns at [expr $now + $intervalTime] "sendPingPacket"
}
BEGIN{
drop=0;
}
{
if($1= ="d" )
{
drop++;
}
} END{
printf("Total number of %s packets dropped due to congestion =%d\n",$5,drop);
Output:
3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and
plotcongestion window for different source / destination.
File : lab3.tcl
$ns trace-all $f
$ns namtrace-all $nf
#define findWindowSize
proc findWindowSize {tcpSource outFile} {
global ns
set now [$ns now]
set cWindSize [$tcpSource set cwnd_]
puts $outFile "$now $cWindSize"
$ns at [expr $now + 0.1] "findWindowSize $tcpSource $outFile"
}
Output:
Implement the following in Java:
4. Write a program for error detecting code using CRC-CCITT (16- bits)
Program:
import java.io.*;
class crc
{
public static void main(String a[]) throws IOException
{
gen=new int[gen_bits];
System.out.println("\n Enter gen bits : ");
for(int i=0; i<gen_bits; i++)
{
gen[i]=Integer.parseInt(br.readLine());
}
total_bits=message_bits+gen_bits-1;
app_message=new int[total_bits];
rem=new int[total_bits];
trans_message=new int[total_bits];
for(int i=0;i<message.length;i++)
{
app_message[i]=message[i];
}
for(int i=0;i<app_message.length;i++)
{
trans_message[i]=(app_message[i]^rem[i]);
}
PROGRAM:
import java.util.Scanner;
public class BellmanFord
{
private int distances[];
private int numberofvertices;
public static final int MAX_VALUE = 999;
public BellmanFord(int numberofvertices)
{
this.numberofvertices = numberofvertices;
distances = new int[numberofvertices + 1];
}
public void BellmanFordEvaluation(int source, int destination,
int adjacencymatrix[][])
{
for (int node = 1; node <= numberofvertices; node++)
{
distances[node] = MAX_VALUE;
}
distances[source] = 0;
for (int node = 1; node <= numberofvertices - 1; node++)
{
for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++)
{
for (int destinationnode = 1; destinationnode <= numberofvertices;
destinationnode++)
{
if (adjacencymatrix[sourcenode][destinationnode] !=
MAX_VALUE)
{
if (distances[destinationnode] > distances[sourcenode]
+ adjacencymatrix[sourcenode][destinationnode])
distances[destinationnode] = distances[sourcenode]
+ adjacencymatrix[sourcenode][destinationnode];
}
}
}
}
for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++)
{
for (int destinationnode = 1; destinationnode <= numberofvertices;
destinationnode++)
{
if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE)
{
if (distances[destinationnode] > distances[sourcenode]
+ adjacencymatrix[sourcenode][destinationnode])
System.out.println("The Graph contains negative egde cycle");
} }
}
for (int vertex = 1; vertex <= numberofvertices; vertex++)
{
if (vertex == destination)
System.out.println("distance of source " + source + " to “ + vertex + " is " +
distances[vertex]);
}
}
public static void main(String... arg)
{
int numberofvertices = 0;
int source, destination;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter the number of vertices");
numberofvertices = scanner.nextInt();
int adjacencymatrix[][] = new int[numberofvertices + 1][numberofvertices
+ 1];
System.out.println("Enter the adjacency matrix");
for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++)
{
for (int destinationnode = 1; destinationnode <= numberofvertices;
destinationnode++)
{
adjacencymatrix[sourcenode][destinationnode] = scanner
.nextInt();
if (sourcenode == destinationnode)
{
adjacencymatrix[sourcenode][destinationnode] = 0;
continue;
}
if (adjacencymatrix[sourcenode][destinationnode] == 0)
{
adjacencymatrix[sourcenode][destinationnode] = MAX_VALUE;
}
}
}
System.out.println("Enter the source vertex");
source = scanner.nextInt();
System.out.println("Enter the destination vertex: ");
destination = scanner.nextInt();
BellmanFord bellmanford = new BellmanFord(numberofvertices);
bellmanford.BellmanFordEvaluation(source, destination,
adjacencymatrix);
scanner.close();
}
}
OUTPUT: Enter the number of vertices 5
Enter the adjacency matrix
0 999 6 3 999
3 0 999 999 999
999 999 0 2 999
999 1 1 0 999
999 4 999 2 0
Enter the source vertex
5
Enter the destination vertex
1
Distance of source 5 to 1 is 6
7. Using TCP/IP sockets, write a client – server program to make the client send the
file name and to make the server send back the contents of the requested file if present.
Implement the above program using as message queues or FIFOs as IPC channels.
Client side:
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.InputStreamReader;
import java.io.DataOutputStream;
//import java.io.OutputStreamWriter;
//import java.net.InetAddress;
import java.net.Socket;
import java.io.File;
import java.io.FileOutputStream;
import java.util.Scanner;
class client
{
public static void main(String args[])throws Exception
{
String address="";
Scanner sc= new Scanner(System.in);
System.out.println("eneter server address");
address=sc.nextLine();
Socket s=new Socket(address,5000);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("snd get to start");
String str="",filename="";
try
{
while(!str.equals("start"))
str=br.readLine();
dout.writeUTF(str);
dout.flush();
filename=din.readUTF();
System.out.println("receiveing file:"+filename);
filename="client"+filename;
System.out.println("saving as file"+filename);
long sz=Long.parseLong(din.readUTF());
System.out.println("filesize:"+(sz/(1024))+"KB");
byte b[]=new byte[1024];
System.out.println("receiving file");
FileOutputStream fos=new FileOutputStream(new File(filename),true);
long bytesRead;
do
{
bytesRead=din.read(b,0,b.length);
fos.write(b,0,b.length);
}
while(!(bytesRead<1024));
System.out.println("completed");
fos.close();
dout.close();
s.close();
}
catch(Exception e)
{
//do nothing;
}
}
}
Server side:
import java.io.InputStreamReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.io.File;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.util.Scanner;
class Server
{
public static void main(String args[])throws Exception
{
String filename;
System.out.println("eneter filename");
Scanner sc= new Scanner(System.in);
filename=sc.nextLine();
sc.close();
while(true)
{
ServerSocket ss =new ServerSocket(5000);
System.out.println("wait fr req");
Socket s=ss.accept();
System.out.println("connected with" +s.getInetAddress().toString());
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
try
{
String str="";
str=din.readUTF();
System.out.println("send get tok ");
if(!str.equals("stop"))
{
System.out.println("sendinf file:"+filename);
dout.writeUTF(filename);
dout.flush();
File f=new File(filename);
FileInputStream fin=new FileInputStream(f);
long sz=(int)f.length();
byte b[]=new byte[1024];
int read;
dout.writeUTF(Long.toString(sz));
dout.flush();
System.out.println("size:"+sz);
System.out.println("buffer size:"+ss.getReceiveBufferSize());
while((read=fin.read(b))!=-1)
{
dout.write(b,0,read);
dout.flush();
}
fin.close();
System.out.println("ok");
dout.flush();
}
dout.writeUTF("stop");
System.out.println("sendi complete");
dout.flush();
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("erroe occuerrd");
}
din.close();
s.close();
ss.close();
}
}
}
Output:
1. Open two terminals and create files client.java and Server.java
2. Open a terminal and run the server program and provide the filename to send
3.Open one more terminal,run the client programand provide the IP address of the
server(Loopback address)
4.Type “start” at the client side.
Server side:
Client side:
8. Write a program on datagram socket for client/server to display the messages on
client side, typed at the server side.
PROGRAM:
import java.net.*;
class datagram {
public static int serverPort = 666;
public static int clientPort = 999;
public static int buffer_size = 1024;
public static DatagramSocket ds;
public static byte buffer[] = new byte[buffer_size];
public static void TheServer() throws Exception {
int pos=0;
while (true) {
int c = System.in.read();
switch(c) {
case -1:
System.out.println("Server Quits.");
return;
case '\r':
break;
case '\n':
ds.send(new DatagramPacket(buffer,pos,InetAddress.getLocalHost(),clientPort));
pos=0;
break;
default:
buffer[pos++] = (byte) c;
}
}
}
public static void TheClient() throws Exception {
while(true) {
DatagramPacket p = new DatagramPacket(buffer, buffer.length);
ds.receive(p);
System.out.println(new String(p.getData(), 0, p.getLength()));
}
}
public static void main(String args[]) throws Exception {
if(args.length == 1) {
ds = new DatagramSocket(serverPort);
TheServer();
} else {
ds = new DatagramSocket(clientPort);
TheClient();
}
}
}
OUTPUT:
Open 2 terminals
In 1st terminal : javac datagram.java
Java datagram
In 2nd terminal :javac datagram.java
Java datagram 1
Server side
PROGRAM:
import java.io.DataInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
import java.util.*;
public encrypt()
{
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);
}
@SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException
{
encrypt encrypt = new encrypt();
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 = encrypt.encrypt(teststring.getBytes());
// decrypt
byte[] decrypted = encrypt.decrypt(encrypted);
System.out.println("Decrypting Bytes: " + bytesToString(decrypted));
System.out.println("Decrypted String: " + new String(decrypted));
}
// 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:
Enter the plain text:
hi
Encrypting String:hi
String in Bytes: 104105
Decrypting Bytes: 104105
Decrypting String: hi
10. Write a program for congestion control using leaky bucket algorithm.
PROGRAM:
import java.util.*;
public class leaky
{
public static void main(String[] args)
{
Scanner my = new Scanner(System.in);
int no_groups,bucket_size;
System.out.print("\n Enter the bucket size : \t");
bucket_size = my.nextInt();
System.out.print("\n Enter the no of groups : \t");
no_groups = my.nextInt();
int no_packets[] = new int[no_groups];
int in_bw[] = new int[no_groups];
int out_bw,reqd_bw=0,tot_packets=0;
for(int i=0;i<no_groups;i++)
{
System.out.print("\n Enter the no of packets for group " + (i+1) + "\t");
no_packets[i] = my.nextInt();
System.out.print("\n Enter the input bandwidth for the group " + (i+1) + "\t");
in_bw[i] = my.nextInt();
if((tot_packets+no_packets[i])<=bucket_size)
{
tot_packets += no_packets[i];
}
else
{
do
{
System.out.println(" Bucket Overflow ");
System.out.println(" Enter value less than " + (bucket_size-tot_packets));
no_packets[i] = my.nextInt();
}while((tot_packets+no_packets[i])>bucket_size);
tot_packets += no_packets[i];
}
reqd_bw += (no_packets[i]*in_bw[i]);
}
System.out.println("\nThe total required bandwidth is " + reqd_bw);
System.out.println("Enter the output bandwidth ");
out_bw = my.nextInt();
int temp=reqd_bw;
int rem_pkts = tot_packets;
while((out_bw<=temp)&&(rem_pkts>0))
{
System.out.println("Data Sent \n" + (--rem_pkts) + " packets remaining");
System.out.println("Remaining Bandwidth " + (temp -= out_bw));
if((out_bw>temp)&&(rem_pkts>0))
System.out.println(rem_pkts + " packet(s) discarded due to insufficient
bandwidth");
}
}
}
OUTPUT:Enter the bucket size:5
Enter the no of groups:1
Enter the no of packets for group1:5
Enter the input bandwidth for the group1:6
The total required bandwidth is 30
Enter the output bandwidth
25
Data sent
4 packets remaining
Remaining Bandwidth: 5
4 packets discarded due to insufficient bandwidth