0% found this document useful (0 votes)
144 views41 pages

CN Lab Manual 2023 24

The document summarizes the experiments and simulations to be conducted in the Computer Networks Laboratory. It includes: 1) Seven experiments on implementing different network topologies and protocols like Ethernet LAN, error detection codes, and congestion control algorithms. 2) An introduction to the network simulator NS-2, describing its architecture and basic components like nodes, links, queues, and protocols that can be simulated. 3) The steps to initialize and terminate a network simulation in NS-2, including defining the network topology, configuring traffic, and collecting output.

Uploaded by

sanjayv7210
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
144 views41 pages

CN Lab Manual 2023 24

The document summarizes the experiments and simulations to be conducted in the Computer Networks Laboratory. It includes: 1) Seven experiments on implementing different network topologies and protocols like Ethernet LAN, error detection codes, and congestion control algorithms. 2) An introduction to the network simulator NS-2, describing its architecture and basic components like nodes, links, queues, and protocols that can be simulated. 3) The steps to initialize and terminate a network simulation in NS-2, including defining the network topology, configuring traffic, and collecting output.

Uploaded by

sanjayv7210
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

Computer Networks Laboratory 2023-2024

COMPUTER NETWORK LABORATORY

Lab Experiments
1. Implement three nodes point – to – point network with duplex links between them for different
topologies. Set the queue size, vary the bandwidth and find the number of packets dropped for
various iterations.
2. Implement simple ESS and with transmitting nodes in wire-less LAN by simulation and
determine the performance with respect to transmission of packets.
3. Write a program for error detecting code using CRC-CCITT (16- bits).
4. 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.
5. Write a program to find the shortest path between vertices using bellman-ford algorithm.
6. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot congestion
window for different source / destination.
7. Write a program for congestion control using leaky bucket algorithm.

Dept. of ISE, APSCE, Bangalore Page 1


Computer Networks Laboratory 2023-2024

Simulation

Introduction to NS-2:
Widely known as NS2, is simply an event driven simulation tool.
Useful in studying the dynamic nature of communication networks.
Simulation of wired as well as wireless network functions and protocols (e.g.,
routing algorithms, TCP, UDP) can be done using NS2.
In general, NS2 provides users with a way of specifying such network protocols and
simulating their corresponding behaviors.

Basic Architecture of NS2

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
Syntax: command arg1 arg2 arg3
Hello World!
puts stdout{Hello, World!}
Hello, World!

Dept. of ISE, APSCE, Bangalore Page 2


Computer Networks Laboratory 2023-2024

Variables Command Substitution


set a 5 set len [string length foobar]
set b $a set len [expr [string length foobar] + 9]
Simple Arithmetic
expr 7.2 / 4
Procedures
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]” Output: Diagonal of a 3, 4 right triangle is 5.0
Loops
while{$i < $n} {
for {set i 0} {$i < $n} {incr i} {
...
...
}
}
Wired TCL Script Components
Create the event scheduler
Open new files & turn on the tracing
Create the nodes
Setup the links
Configure the traffic type (e.g., TCP, UDP, etc)
Set the time of traffic generation (e.g., CBR, FTP)
Terminate the simulation

NS Simulator Preliminaries.
1. Initialization and termination aspects of the ns simulator.
2. Definition of network nodes, links, queues and topology.
3. Definition of agents and of applications.
4. The nam visualization tool.
5. Tracing and random variables.

Dept. of ISE, APSCE, Bangalore Page 3


Computer Networks Laboratory 2023-2024

Initialization and Termination of TCL Script in NS-2 An


ns simulation starts with the command

set ns [new Simulator]

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

Dept. of ISE, APSCE, Bangalore Page 4


Computer Networks Laboratory 2023-2024

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

Definition of a network of links and nodes


The way to define a node is

set n0 [$ns node]

Dept. of ISE, APSCE, Bangalore Page 5


Computer Networks Laboratory 2023-2024

The node is created which is printed by the variable n0. When we shall refer to that node in the
script we shall thus write $n0.

Once we define several nodes, we can define the links that connect them. An example of a
definition of a link is:

$ns duplex-link $n0 $n2 10Mb

Which means that $n0 and $n2 are connected using a bi-directional link that has 10ms of
propagation delay and a capacity of 10Mb per sec for each direction.

To define a directional link instead of a bi-directional one, we should replace “duplex-


link” by “simplex-link”.

In NS, an output queue of a node is implemented as a part of each link whose input is that
node. The definition of the link then includes the way to handle overflow at that queue. In our
case, if the buffer capacity of the output queue is exceeded then the last packet to arrive is
dropped. Many alternative options exist, such as the RED (Random Early Discard) mechanism,
the FQ (Fair Queuing), the DRR (Deficit Round Robin), the stochastic Fair Queuing (SFQ) and
the CBQ (which including a priority and a round-robin scheduler).

In ns, an output queue of a node is implemented as a part of each link whose input is that
node. We should also define the buffer capacity of the queue related to each link. An example

#set Queue Size of link (n0 n2) to 20


$ns queue-limit $n0 $n2 20

We need to define routing (sources, destinations) the agents (protocols) the application that use
them.
TCP is a dynamic reliable congestion control protocol. It uses
FTP over TCP
Acknowledgements created by the destination to know whether packets are well
received.
There are number variants of the TCP protocol, such as Tahoe, Reno, NewReno, Vegas.
The type of agent appears in the first line:

Dept. of ISE, APSCE, Bangalore Page 6


Computer Networks Laboratory 2023-2024

set tcp [new Agent/TCP]

The command $ns attach-agent $n0 $tcp defines the source node of the tcp connection.
The command
set sink [new Agent /TCPSink]

Defines the behavior of the destination node of TCP and assigns to it a pointer called sink.

#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


The below shows the definition of a CBR application using a UDP agent
The command $ns attach-agent $n4 $sink defines the destination node. The command
$ns connect $tcp $sink finally makes the TCP connection between the source and destination
nodes.

set cbr [new


Application/Traffic/CBR]

$cbr attach-agent $udp

$cbr set packetsize_ 100

$cbr set rate_ 0.01Mb

$cbr set random_ false

Dept. of ISE, APSCE, Bangalore Page 7


Computer Networks Laboratory 2023-2024

TCP has many parameters with initial fixed defaults values that can be changed if
mentioned explicitly. For example, the default TCP packet size has a size of 1000bytes.This can
be changed to another value, say 552bytes, using the command $tcp set packetSize_ 552.
When we have several flows, we may wish to distinguish them so that we can identify
them with different colors in the visualization part. This is done by the command $tcp set fid_ 1
that assigns to the TCP connection a flow identification of “1”.We shall later give the flow
identification of “2” to the UDP connection.

CBR over UDP


A UDP source and destination is defined in a similar way as in the case of TCP.
Instead of defining the rate in the command $cbr set rate_ 0.01Mb, one can define the
time interval between transmission of packets using the command.

$cbr set interval_ 0.005

The packet size can be set to some value using

$cbr set packetSize_ <packet size>

Scheduling Events
NS is a discrete event based simulation. The tcp script defines when event should occur.
The initializing command set ns [new Simulator] creates an event scheduler, and events are then
scheduled using the format:

$ns at <time> <event>


The scheduler is started when running ns that is through the command $ns run.
The beginning and end of the FTP and CBR application can be done through the following
command
$ns at 0.1 “$cbr start”
$ns at 1.0 “ $ftp start”
$ns at 124.0 “$ftp stop”
$ns at 124.5 “$cbr stop”

Dept. of ISE, APSCE, Bangalore Page 8


Computer Networks Laboratory 2023-2024

Structure of Trace Files


When tracing into an output ASCII file, the trace is organized in 12 fields as follows in
fig shown below, The meaning of the fields are:
Event Time From To PKT PKT Flags Fid Src Dest Seq Pkt
Node Node Type Size Addr Addr Num id

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.

Dept. of ISE, APSCE, Bangalore Page 9


Computer Networks Laboratory 2023-2024

XGRAPH

The xgraph program draws a graph on an x-display given data read from either data file
or from standard input if no files are specified. It can display upto 64 independent data sets using
different colors and line styles for each set. It annotates the graph with a title, axis labels, grid
lines or tick marks, grid labels and a legend.

Syntax:
Xgraph [options] file-name

Options are listed here


/-bd <color> (Border)
This specifies the border color of the xgraph window.
/-bg <color> (Background)
This specifies the background color of the xgraph window.
/-fg<color> (Foreground)
This specifies the foreground color of the xgraph window.
/-lf <fontname> (LabelFont)
All axis labels and grid labels are drawn using this font.
/-t<string> (Title Text)
This string is centered at the top of the graph.
/-x <unit name> (XunitText)
This is the unit name for the x-axis. Its default is “X”.
/-y <unit name> (YunitText)
This is the unit name for the y-axis. Its default is “Y”.

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

Dept. of ISE, APSCE, Bangalore Page 10


Computer Networks Laboratory 2023-2024

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)

Here, selection_criteria filters input and select lines for the action component to act upon.
The selection_criteria is enclosed within single quotes and the action within the curly braces.
Both the selection_criteria and action forms an awk program.
Example: $ awk „/manager/ {print}‟ emp.lst

Variables
Awk allows the user to use variables of there choice. You can now print a serial number,
using the variable kount, and apply it those directors drawing a salary exceeding 6700:
$ awk –F”|” „$3 == “director” && $6 > 6700 {
kount =kount+1
printf “ %3f %20s %-12s %d\n”, kount,$2,$3,$6 }‟ empn.lst

THE –f OPTION: STORING awk PROGRAMS IN A FILE


You should holds large awk programs in separate file and provide them with the awk
extension for easier identification. Let‟s first store the previous program in the file empawk.awk:
$ cat empawk.awk
Observe that this time we haven‟t used quotes to enclose the awk program. You can now
use awk with the –f filename option to obtain the same output:

Awk –F”|” –f empawk.awk empn.lst

The BEGIN and END Sections


Awk statements are usually applied to all lines selected by the address, and if there are no
addresses, then they are applied to every line of input. But, if you have to print something before
processing the first line, for example, a heading, then the BEGIN section can be used gainfully.
Similarly, the end section useful in printing some totals after processing is over. The BEGIN and
END sections are optional and take the form

Dept. of ISE, APSCE, Bangalore Page 11


Computer Networks Laboratory 2023-2024

BEGIN {action}
END {action}
These two sections, when present, are delimited by the body of the awk program. You
can use them to print a suitable heading at the beginning and the average salary at the end.
Built-In Variables
Awk has several built-in variables. They are all assigned automatically, though it is also
possible for a user to reassign some of them. You have already used NR, which signifies the
record number of the current line. We‟ll now have a brief look at some of the other variable.
The FS Variable: as stated elsewhere, awk uses a contiguous string of spaces as the default field
delimiter. FS redefines this field separator, which in the sample database happens to be the |.
When used at all, it must occur in the BEGIN section so that the body of the program knows its
value before it starts processing:
BEGIN {FS=”|”}
This is an alternative to the –F option which does the same thing.
The OFS Variable: when you used the print statement with comma-separated arguments, each
argument was separated from the other by a space. This is awk‟s default output field separator,
and can reassigned using the variable OFS in the BEGIN section:
BEGIN { OFS=”~” }
When you reassign this variable with a ~ (tilde), awk will use this character for delimiting the
print arguments. This is a useful variable for creating lines with delimited fields.
The NF variable: NF comes in quite handy for cleaning up a database of lines that don‟t contain
the right number of fields. By using it on a file, say emp.lst, you can locate those lines not having
6 fields, and which have crept in due to faulty data entry:
$awk „BEGIN {FS = “|”}
NF! =6 {
Print “Record No “, NR, “has”, “fields”}‟ empx.lst

Dept. of ISE, APSCE, Bangalore Page 12


Computer Networks Laboratory 2023-2024

Experiment 1
1. Implement three nodes point – to – point network with duplex links between them for
different topologies. Set the queue size, vary the bandwidth and find the number of
packets dropped for various iterations.

Step1: Open text editor, type the below program and save with extention .tcl (prog1.tcl )

set ns [new Simulator]


set nf [open prog1.nam w]
$ns namtrace-all $nf
set nd [open prog1.tr w]
$ns trace-all $nd

proc finish { } {
global ns nf nd
$ns flush-trace
close $nf
close $nd
exec nam prog1.nam &
exit 0
}

set n0 [$ns node]


set n1 [$ns node]
set n2 [$ns node]

$ns duplex-link $n0 $n1 1Mb 10ms DropTail


$ns duplex-link $n1 $n2 512kb 10ms DropTail
$ns queue-limit $n1 $n2 10

set udp0 [new Agent/UDP]


$ns attach-agent $n0 $udp0
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set sink [new Agent/Null]
$ns attach-agent $n2 $sink
$ns connect $udp0 $sink

Dept. of ISE, APSCE, Bangalore Page 13


Computer Networks Laboratory 2023-2024

$ns at 0.2 "$cbr0 start"


$ns at 4.5 "$cbr0 stop"
$ns at 5.0 "finish"
$ns run

Step2: Open text editor, type the below program and save with extention .awk (prog1.awk )

BEGIN {
dcount = 0;
rcount = 0;
}
{
event = $1;
if(event == "d")
{
dcount++;
}
if(event == "r")
{
rcount++;
}
}
END {
printf("The no.of packets dropped : %d\n ",dcount);
printf("The no.of packets recieved : %d\n ",rcount);
}
Step3: Run the simulation program
[root@localhost~]# ns prog1.tcl
(Here “ns” indicates network simulator. We get the topology shown in the snapshot.)

Dept. of ISE, APSCE, Bangalore Page 14


Computer Networks Laboratory 2023-2024

Step 4: Now press the play button in the simulation window and the simulation will begins.

Step 5: After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f prog1.awk prog1.tr
Number of packets droped = 16

Step 6: To see the trace file contents open the file as ,


[root@localhost~]# vi prog1.tr

Dept. of ISE, APSCE, Bangalore Page 15


Computer Networks Laboratory 2023-2024

Experiment 2:

Implement simple ESS and with transmitting nodes in wire-less LAN by simulation and
determine the throughput with respect to transmission of packets.

Step1: Open text editor, type the below program and save with extention .tcl (prog2.tcl )

set ns [new Simulator]


set tf [open prog2.tr w]
$ns trace-all $tf
set topo [new Topography]
$topo load_flatgrid 1000 1000
set nf [open prog6.nam w]
$ns namtrace-all-wireless $nf 1000 1000
set val(chan) Channel/WirelessChannel ;
set val(prop) Propagation/TwoRayGround ;

set val(netif) Phy/WirelessPhy ;


set val(mac) Mac/802_11 ;
set val(ifq) Queue/DropTail/PriQueue ;
set val(ll) LL ;
set val(ant) Antenna/OmniAntenna ;
set val(ifqlen) 50 ;
set val(nn) 2 ;
set val(rp) AODV ;
set val(x) 500 ;
set val(y) 400 ;
set val(stop) 10.0 ;

$ns node-config -adhocRouting $val(rp) \


-llType $val(ll) \
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
-channelType $val(chan) \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \

Dept. of ISE, APSCE, Bangalore Page 16


Computer Networks Laboratory 2023-2024

-macTrace OFF \
-movementTrace ON

create-god 3
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]

$n0 label "tcp0"


$n1 label "sink1/tcp1"
$n2 label "sink2"

$n0 set X_ 50
$n0 set Y_ 50
$n0 set Z_ 0
$n1 set X_ 100
$n1 set Y_ 100
$n1 set Z_ 0
$n2 set X_ 600
$n2 set Y_ 600
$n2 set Z_ 0
$ns at 0.1 "$n0 setdest 50 50 15"
$ns at 0.1 "$n1 setdest 100 100 25"
$ns at 0.1 "$n2 setdest 600 600 25"
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
set sink1 [new Agent/TCPSink]
$ns attach-agent $n1 $sink1
$ns connect $tcp0 $sink1
set tcp1 [new Agent/TCP]
$ns attach-agent $n1 $tcp1
set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
set sink2 [new Agent/TCPSink]
$ns attach-agent $n2 $sink2
$ns connect $tcp1 $sink2
$ns at 5 "$ftp0 start"
$ns at 5 "$ftp1 start"

Dept. of ISE, APSCE, Bangalore Page 17


Computer Networks Laboratory 2023-2024

$ns at 100 "$n1 setdest 550 550 15"


$ns at 190 "$n1 setdest 70 70 15"
proc finish { } {
global ns nf tf
$ns flush-trace
exec nam prog4.nam &
close $tf
exit 0
}
$ns at 250 "finish"
$ns run

Step2: Open text editor, type the below program and save with extention .awk (prog4.awk )

BEGIN{
count1=0
count2=0
pack1=0
pack2=0
time1=0
time2=0
}
{if($1=="r"&& $3=="_1_" && $4=="AGT")
{count1++
pack1=pack1+$8
time1=$2 }
if($1=="r" && $3=="_2_" && $4=="AGT")
{count2++
pack2=pack2+$8
time2=$2}
}
END{
printf("The Throughput from n0 to n1: %f Mbps \n", ((count1*pack1*8)/(time1*1000000)));
printf("The Throughput from n1 to n2: %f Mbps", ((count2*pack2*8)/(time2*1000000)));
}

Step3: Run the simulation program


[root@localhost~]# ns prog4.tcl
(Here “ns” indicates network simulator. We get the topology shown in the snapshot.)

Dept. of ISE, APSCE, Bangalore Page 18


Computer Networks Laboratory 2023-2024

Step 4: Now press the play button in the simulation window and the simulation will begins

Dept. of ISE, APSCE, Bangalore Page 19


Computer Networks Laboratory 2023-2024

Step 5: After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f prog4.awk prog6.tr

Step6: type vi prog6.tr

Here “M” indicates mobile nodes, “AGT” indicates Agent Trace, “RTR” indicates Router

Dept. of ISE, APSCE, Bangalore Page 20


Computer Networks Laboratory 2023-2024
Experiment 3

Write a program for error detecting code using CRC-CCITT (16 bits).

Theory

CRC(Cyclic Redundancy Check) is an error detecting technique used in digital networks and
storage devices to detect the accidental changes to raw data. It cannot be used for correcting
errors.

If an error is detected in the received message, a „Negative acknowledgement‟ is sent to


the sender. The sender and the receiver agree upon a fixed polynomial called generator
polynomial. The standard agreed generator polynomial is x16+x12+x5+x0 (any polynomial can be
considered, of degree 16).

The CRC does error checking via polynomial division. The generated polynomial g(x) =
x +x +x5+x0
16 12

16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0

17 bits.
1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 1

So the g(x) value is 10001000000100001

Algorithm:

1. Given a bit string (message to be sent), append 16 0S to the end of it (the number of 0s is
the same as the degree of the generator polynomial) let this string + 0S be called as
modified string B
2. Divide B by agreed on polynomial g(x) and determine the remainder R(x). The 16-bit
remainder received is called as checksum.
3. The message string is appended with checksum and sent to the receiver.
4. At the receiver side, the received message is divided by generator polynomial g(x).
5. If the remainder is 0, the receiver concludes that there is no error occurred otherwise, the
receiver concludes an error occurred and requires a retransmission.

Dept. of ISE, APSCE, Bangalore Page 21


Computer Networks Laboratory 2023-2024

PROGRAM:
import java.io.*;
class crc_gen
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
int[] data;
int[] div;
int[] divisor;
int[] rem;
int[] crc;
int data_bits, divisor_bits, tot_length;

System.out.println("Enter number of data bits :");


data_bits=Integer.parseInt(br.readLine());
data=new int[data_bits];

System.out.println("Enter data bits : ");


for(int i=0; i<data_bits; i++)
data[i]=Integer.parseInt(br.readLine());

divisor_bits = 17;
divisor = new int[]{1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1};

tot_length=data_bits+divisor_bits-1;

div=new int[tot_length];
rem=new int[tot_length];
crc=new int[tot_length];
/* CRC GENERATION */
for(int i=0;i<data.length;i++)
div[i]=data[i];

System.out.print("Dividend (after appending 0's) are : ");


for(int i=0; i< div.length; i++)
System.out.print(div[i]);
System.out.println();

for(int j=0; j<div.length; j++){

Dept. of ISE, APSCE, Bangalore Page 22


Computer Networks Laboratory 2023-2024

rem[j] = div[j];
}

rem=divide(divisor, rem);

for(int i=0;i<div.length;i++) //append dividend and ramainder


{
crc[i]=(div[i]^rem[i]);
}

System.out.println();
System.out.println("CRC code : ");
for(int i=0;i<crc.length;i++)
System.out.print(crc[i]);

/* ERROR DETECTION */
System.out.println();
System.out.println("Enter CRC code of "+tot_length+" bits :
"); for(int i=0; i<crc.length; i++)
crc[i]=Integer.parseInt(br.readLine());

for(int j=0; j<crc.length; j++){


rem[j] = crc[j];
}

rem=divide(divisor, rem);

for(int i=0; i< rem.length; i++)


{
if(rem[i]!=0)
{
System.out.println("Error");
break;
}
if(i==rem.length-1)
System.out.println("No Error");
}

System.out.println("THANK YOU. .... )");

Dept. of ISE, APSCE, Bangalore Page 23


Computer Networks Laboratory 2023-2024

static int[] divide(int divisor[], int rem[])


{
int cur=0;
while(true)
{
for(int i=0;i<divisor.length;i++)
rem[cur+i]=(rem[cur+i]^divisor[i]);

while(rem[cur]==0 && cur!=rem.length-1)


cur++;

if((rem.length-cur)<divisor.length)
break;
}
return rem;
}
}

OUTPUT:

Dept. of ISE, APSCE, Bangalore Page 24


Computer Networks Laboratory 2023-2024

Dept. of ISE, APSCE, Bangalore Page 25


Computer Networks Laboratory 2023-2024

Experiment 4:

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 in the network.

Step1: Open text editor, type the below program and save with extention .tcl (prog2.tcl )

set ns [new Simulator]


set nf [open prog2.nam w]
$ns namtrace-all $nf
set nd [open prog2.tr w]
$ns trace-all $nd

proc finish {} {
global ns nf nd
$ns flush-trace
close $nf
close $nd
exec nam prog2.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]

$ns duplex-link $n1 $n0 1Mb 10ms DropTail


$ns duplex-link $n2 $n0 1Mb 10ms DropTail
$ns duplex-link $n3 $n0 1Mb 10ms DropTail
$ns duplex-link $n4 $n0 1Mb 10ms DropTail
$ns duplex-link $n5 $n0 1Mb 10ms DropTail
$ns duplex-link $n6 $n0 1Mb 10ms DropTail

Agent/Ping instproc recv {from rtt} {


$self instvar node_
puts "node [$node_ id] recieved ping answer from \
$from with round-trip-time $rtt ms." }

Dept. of ISE, APSCE, Bangalore Page 26


Computer Networks Laboratory 2023-2024

set p1 [new Agent/Ping]


set p2 [new Agent/Ping]
set p3 [new Agent/Ping]
set p4 [new Agent/Ping]
set p5 [new Agent/Ping]
set p6 [new Agent/Ping]

$ns attach-agent $n1 $p1


$ns attach-agent $n2 $p2
$ns attach-agent $n3 $p3
$ns attach-agent $n4 $p4
$ns attach-agent $n5 $p5
$ns attach-agent $n6 $p6

$ns queue-limit $n0 $n4 3


$ns queue-limit $n0 $n5 2
$ns queue-limit $n0 $n6 2

$ns connect $p1 $p4


$ns connect $p2 $p5
$ns connect $p3 $p6

$ns at 0.2 "$p1 send"


$ns at 0.4 "$p2 send"
$ns at 0.6 "$p3 send"
$ns at 1.0 "$p4 send"
$ns at 1.2 "$p5 send"
$ns at 1.4 "$p6 send"
$ns at 2.0 "finish"
$ns run

Step2: Open text editor, type the below program and save with extention .awk (prog2.awk )
BEGIN {
count=0;
}
{
event=$1;
if(event=="d")
{
count++;

Dept. of ISE, APSCE, Bangalore Page 27


Computer Networks Laboratory 2023-2024

}
}
END {
printf("No of packets dropped : %d\n",count);
}

Step3: Run the simulation program


[root@localhost~]# ns prog2.tcl
(Here “ns” indicates network simulator. We get the topology shown in the snapshot.)

Dept. of ISE, APSCE, Bangalore Page 28


Computer Networks Laboratory 2023-2024

Step 4: Now press the play button in the simulation window and the simulation will begins.
Step 5: After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f prog2.awk prog2.tr

Step 6: To see the trace file contents open the file as ,


[root@localhost~]# vi prog2.tr

Dept. of ISE, APSCE, Bangalore Page 29


Computer Networks Laboratory 2023-2024

Experiment 5
Bellman-Ford algorithm

Problem Statement

Write a program to find the shortest path between vertices using bellman-ford algorithm.

Theory
Routing algorithm is a part of network layer software which is responsible for deciding which
output line an incoming packet should be transmitted on. If the subnet uses datagram internally,
this decision must be made anew for every arriving data packet since the best route may have
changed since last time. If the subnet uses virtual circuits (connection Oriented), routing
decisions are made only when a new established route is being set up.

Routing algorithms can be grouped into two major classes: adaptive and nonadaptive.
Nonadaptive algorithms do not base their routing decisions on measurement or estimates of
current traffic and topology. Instead, the choice of route to use to get from I to J (for all I and J)
is compute in advance, offline, and downloaded to the routers when the network ids booted. This
procedure is sometime called static routing.

Adaptive algorithms, in contrast, change their routing decisions to reflect changes in the
topology, and usually the traffic as well. Adaptive algorithms differ in where they get
information (e.g., locally, from adjacent routers, or from all routers), when they change the
routes (e.g., every ∆T sec, when the load changes, or when the topology changes), and what
metric is used for optimization (e.g., distance, number of hops, or estimated transit time).

Two algorithms in particular, distance vector routing and link state routing are the most
popular. Distance vector routing algorithms operate by having each router maintain a table (i.e.,
vector) giving the best known distance to each destination and which line to get there. These
tables are updated by exchanging information with the neighbors.

The distance vector routing algorithm uses Bellman-Ford routing algorithm and Ford-
Fulkerson algorithm. In distance vector routing, each router maintains a routing table that
contains two parts: the preferred out going line to use for that destination, and an estimate of the
time or distance to that destination. The metric used might be number of hops, time delay in
milliseconds, total number of packets queued along the path, or something similar.

The Routing tables are shared among the neighbors, and the tables at the router are updated,
such that the router will know the shortest path to the destination.

Program
import java.io.*;
import java.util.Scanner;
class dist_vec
{
public static void main(String args[]) {

Dept. of ISE, APSCE, Bangalore Page 30


Computer Networks Laboratory 2023-2024

int dmat[][];
int dist[][];
int via[][];
int n=0,i=0,j=0,k=0,count=0;
Scanner in = new Scanner(System.in);

System.out.println("enter the number of nodes\n");


n = in.nextInt();

dmat = new int[n][n];


dist = new int[n][n];
via = new int[n][n];
System.out.println("enter the cost matrix\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
dmat[i][j] = in.nextInt();
dmat[i][i]=0;
dist[i][j]=dmat[i][j];
via[i][j]=j;
}
do
{
count=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
for(k=0;k<n;k++)
if(dist[i][j]>dmat[i][k]+dist[k][j])
{
dist[i][j]=dist[i][k]+dist[k][j];
via[i][j]=k;
count++;
}
}while(count!=0);
for(i=0;i<n;i++)
{
System.out.println("state value for router"+i+" is");
for(j=0;j<n;j++)
{
System.out.println("To "+j+" -Via "+via[i][j]+" distance is "+dist[i][j]);
}
}

Dept. of ISE, APSCE, Bangalore Page 31


Computer Networks Laboratory 2023-2024

}
}
OUTPUT

Dept. of ISE, APSCE, Bangalore Page 32


Computer Networks Laboratory 2023-2024
Experiment 6:

Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot
congestion window for different source / destination.

Step1: Open text editor, type the below program and save with extention .tcl (prog3.tcl )

set ns [new Simulator]


set nf [open prog3.nam w]
$ns namtrace-all $nf
set nd [open prog3.tr w]
$ns trace-all $nd

$ns color 1 Blue


$ns color 2 Red

proc finish { } {
global ns nf nd
$ns flush-trace
close $nf
close $nd
exec nam prog3.nam &
exit 0
}

set n0 [$ns node]


set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]
set n6 [$ns node]
set n7 [$ns node]
set n8 [$ns node]

$n7 shape box


$n7 color Blue
$n8 shape hexagon
$n8 color Red

$ns duplex-link $n1 $n0 2Mb 10ms DropTail

Dept. of ISE, APSCE, Bangalore Page 33


Computer Networks Laboratory 2023-2024

$ns duplex-link $n2 $n0 2Mb 10ms DropTail


$ns duplex-link $n0 $n3 1Mb 20ms DropTail

$ns make-lan "$n3 $n4 $n5 $n6 $n7 $n8" 512Kb 40ms LL Queue/DropTail Mac/802_3

$ns duplex-link-op $n1 $n0 orient right-down


$ns duplex-link-op $n2 $n0 orient right-up
$ns duplex-link-op $n0 $n3 orient right

$ns queue-limit $n0 $n3 20

set tcp1 [new Agent/TCP/Vegas]


$ns attach-agent $n1 $tcp1
set sink1 [new Agent/TCPSink]
$ns attach-agent $n7 $sink1
$ns connect $tcp1 $sink1
$tcp1 set class_ 1
$tcp1 set packetsize_ 55

set ftp1 [new Application/FTP]


$ftp1 attach-agent $tcp1

set tfile [open cwnd.tr w]


$tcp1 attach $tfile
$tcp1 trace cwnd_

set tcp2 [new Agent/TCP/Reno]


$ns attach-agent $n2 $tcp2
set sink2 [new Agent/TCPSink]
$ns attach-agent $n8 $sink2
$ns connect $tcp2 $sink2
$tcp2 set class_ 2
$tcp2 set packetSize_ 55

set ftp2 [new Application/FTP]


$ftp2 attach-agent $tcp2

set tfile2 [open cwnd2.tr w]


$tcp2 attach $tfile2
$tcp2 trace cwnd_

Dept. of ISE, APSCE, Bangalore Page 34


Computer Networks Laboratory 2023-2024

$ns at 0.5 "$ftp1 start"


$ns at 1.0 "$ftp2 start"
$ns at 5.0 "$ftp2 stop"
$ns at 5.0 "$ftp1 stop"

$ns at 5.5 "finish"


$ns run

Step2: Open text editor, type the below program and save with extention .awk (prog3.awk )

BEGIN {
}
{
if($6=="cwnd_") {
printf("%f\t%f\n",$1,$7);
}
}
END {
}

Step3: Run the simulation program


[root@localhost~]# ns prog3.tcl
(Here “ns” indicates network simulator. We get the topology shown in the snapshot.)

Step 4: Now press the play button in the simulation window and the simulation will begins.

Dept. of ISE, APSCE, Bangalore Page 35


Computer Networks Laboratory 2023-2024

Step 5: After simulation is completed run awk file and generate the graph ,
[root@localhost~]# awk –f prog3.awk cwnd.tr > a1
[root@localhost~]# awk –f prog3.awk cwnd2.tr > a2
[root@localhost~]#xgraph a1 a2

Step 6: To see the trace file contents open the file as ,


[root@localhost~]# vi prog3.tr

Dept. of ISE, APSCE, Bangalore Page 36


Computer Networks Laboratory 2023-2024

Experiment7
Leaky Bucket

Problem Statement
Write a program for congestion control using leaky bucket algorithm.

Theory
The congesting control algorithms are basically divided into two groups: open loop and closed
loop. Open loop solutions attempt to solve the problem by good design, in essence, to make sure
it does not occur in the first place. Once the system is up and running, midcourse corrections are
not made. Open loop algorithms are further divided into ones that act at source versus ones that
act at the destination.

In contrast, closed loop solutions are based on the concept of a feedback loop if there is any
congestion. Closed loop algorithms are also divided into two sub categories: explicit feedback
and implicit feedback. In explicit feedback algorithms, packets are sent back from the point of
congestion to warn the source. In implicit algorithm, the source deduces the existence of
congestion by making local observation, such as the time needed for acknowledgment to come
back.

The presence of congestion means that the load is (temporarily) greater than the resources (in
part of the system) can handle. For subnets that use virtual circuits internally, these methods can
be used at the network layer.

Another open loop method to help manage congestion is forcing the packet to be transmitted
at a more predictable rate. This approach to congestion management is widely used in ATM
networks and is called traffic shaping.

The other method is the leaky bucket algorithm. Each host is connected to the network by an
interface containing a leaky bucket, that is, a finite internal queue. If a packet arrives at the queue
when it is full, the packet is discarded. In other words, if one or more process are already queued,
the new packet is unceremoniously discarded. This arrangement can be built into the hardware
interface or simulate d by the host operating system. In fact it is nothing other than a single
server queuing system with constant service time.

The host is allowed to put one packet per clock tick onto the network. This mechanism turns
an uneven flow of packet from the user process inside the host into an even flow of packet onto
the network, smoothing out bursts and greatly reducing the chances of congestion.

Dept. of ISE, APSCE, Bangalore Page 37


Computer Networks Laboratory 2023-2024

Program:

import java.lang.*;
import java.util.Random;
import java.io.*;
import java.util.Scanner;
class leaky_bucket
{
public static void main(String args[])
{
int drop=0,mini,nsec,p_remain=0;
int o_rate,b_size,i,packet[];

packet = new int[100];

Scanner in = new Scanner(System.in);

System.out.println("Enter bucket size:");


b_size = in.nextInt();

System.out.println("Enter the output rate:");


o_rate = in.nextInt();
System.out.println("Enter the number of seconds you want to
simulate:"); nsec = in.nextInt();
Random rand = new Random();
for(i=0;i<nsec;i++)
packet[i]=((rand.nextInt(9)+1)*10);
System.out.println("Seconds|packets received|packets sent|packets left|packets dropped");
System.out.println(" ");
for(i=0;i<nsec;i++)
{
p_remain+=packet[i];
if(p_remain>b_size)
{
drop=p_remain-b_size;
p_remain=b_size;
System.out.print(i+1+" ");
System.out.print(packet[i]+" ");
mini=Math.min(p_remain,o_rate);
System.out.print(mini+" ");

Dept. of ISE, APSCE, Bangalore Page 38


Computer Networks Laboratory 2023-2024

p_remain=p_remain-mini;
System.out.print(p_remain+" ");
System.out.print(drop+" ");
System.out.println();
drop=0;
}
}
while(p_remain!=0)

if(p_remain>b_size)

drop=p_remain-b_size;

p_remain=b_size;

mini=Math.min(p_remain,o_rate);

System.out.print("
"+p_remain+"
"+mini);

p_remain=p_remain-mini;

System.out.println(“ “+p_remain+"
"+drop);

drop=0;

Dept. of ISE, APSCE, Bangalore Page 39


Computer Networks Laboratory 2023-2024

Output:

Dept. of ISE, APSCE, Bangalore Page 40


Computer Networks Laboratory 2023-2024

Dept. of ISE, APSCE, Bangalore Page 41

You might also like