You are on page 1of 63

Computer Communication Networks Lab 17TEL77 2020

KAMMAVARI SANGAM ®
K.S.INSTITUTE OF TECHNOLOGY
#14, RAGHUVANAHALLI, KANAKAPURA MAIN ROAD, BANGALORE -560109

(APPROVED BY A.I.C.T.E. AFFILIATED TO VTU)

DEPARTMENT OF TELECOMMUNICATION ENGINEERING

Vision of the Department:


To bestow quality education in Telecommunication Engineering endowed with human values to
secure a better connected society.

Mission of the Department:

M1: To provide effective pedagogy for building and realizing the required knowledge
and skills that constitute a telecom professional.
M2: To impart learning through innovations and team work. With ethical values.
M3: To instill the quest for continuous learning and enhancing their communication skills
through professional bodies and clubs.

COMPUTER COMMUNICATION NETWORKS LAB


15TEL77

Dept. of TCE Page 1


Computer Communication Networks Lab 17TEL77 2020

Dept. of TCE Page 2


Computer Communication Networks Lab 17TEL77 2020

Dept. of TCE Page 3


Computer Communication Networks Lab 17TEL77 2020

Part A
Network Simulator 2 (NS2)
NS2 installation steps

 Step 1: This video shows you the demonstration of NS2 in Linux Mint 18.3 (64Bit) OS
 Step 2: issue this command in the terminal "sudo apt-get install build-essential autoconf
automake
libxmu-dev" (without Quotes)
 Step 3: if you have Ubuntu issue this command first before u try step 2 : "sudo apt-get
update"
 Step 4: Once installation succeeded, start the process of installing NS2
 Step 5: copy the ns-allinone-2.3x.tar.gz in the home folder, in my case it is
/home/USERNAME
 Step 6: go to home folder and execute this command "tar zxvf ns-allinone-2.35.tar.gz"
 step 7: cd ns-allinone-2.35 and ./install (after these commands, wait for the successful
installation),
it may take 5 min to 15 minutes based on the speed of your computer.
 Step 8: there may be errors shown, in case if errors, the errors should be corrected and
reissue the command ./install
 step 9: If there is any error on ns-2.35/linkstate/ls.h file, the error has to be corrected,
change erase to this->erase
 Step 10: Once installation is succeeded, you will get some path information
 Step 11: set the paths in the .profile file which is under the home directory
(/home/hdl1(system name) /.profile), copy the PATH and LD_LIBRARY_PATH URL
and paste in the .profile file.
 Step 12: Once the path information is set, run the command to test the path " source
/home/pradeep/.profile) and see there should not be any errors
 Step 16: Try NS and nam individually and see whether they are working when you
type ns and type enter a % symbol indicates the installation is successful when you
type nam and a network animation window pop up

Nsg2.1

Installation steps

 Step1 : sudo apt-get update"


 Step2 : sudo apt-get install default.jdk

NSG2 is now maintained by Peng-Jung Wu


My advisor : Prof. Chungnan Lee

Creative Inteligence Information System Lab,


Department of Computer Science and Engineering,
National Sun Yat-sen University.

What is NSG2? :

Dept. of TCE Page 4


Computer Communication Networks Lab 17TEL77 2020

NS2 Scenarios Generator 2(NSG2) is a JAVA based ns2 scenarios generator. Since NSG2 is
written by JAVA language, you can run NSG on any platform. NSG2 is capable of generating
both wired and wireless TCL scripts for ns2. Some major functions of NSG2 are listed below:

1. Creating wired and wireless nodes


2. Creating connection between nodes
3. Creating links (Duplex-Link and Simplex-Link)
4. Creating agents (TCP and UDP)
5. Creating applications (CBR and FTP)
6. Node movement
PS. A previous version of NSG that can only generate wireless scenarios can also be found here.

Is NSG2 free?
Yes, it is a free software.
Download NSG2 :
NSG2 (2007/5/20)
NSG2.1 (2008/11/18)
If you still wanna download NSG1 (previous version of NSG), it can be found here.

Launch NSG2 :

To execute NSG2, you have to install JAVA6.0 first. You can download JAVA6.0
from http://java.sun.com/. The details of JAVA6.0 installation, please refer to Sun JAVA site.

NSG2 doesn't need to be installed in your computer. You just download it and launch it with
following instruction under DOS command environment. In fact, on my computer system,
Windows XP, I just double click the NSG2.jar, and NSG2 will automatically launch. If it
doesn't launch, you can also launch NSG2 as following instructions.

General procedure to run the TCL script and verify the output

1. Right click in the folder where NSG is installed to open the terminal.
2. Type „ls„ and check for list of copied files and type the command “ java –jar
NSG2.1.jar”
3. Go the scenario and select “ New wired /wireless scenario”
4. Click on the nodes and place the nodes for the required scenario and connect them with
link between nodes by choosing any one of them below mentioned according to the
requirement.
 Duplex link - > TCP
 Simplex link - > UDP
5. Connect the agent to the nodes suitably [TCP & UDP]
6. Fix the application for the agent as shown
 TCP - > application -> FTP
 UDP - > application -> CBR

Dept. of TCE Page 5


Computer Communication Networks Lab 17TEL77 2020

7. Connect the agent between source node and destination node.


8. Click on parameters in the toolbar & rename trace file and nam file and save it.
9. Click on TCL and generate TCL script for the scenario
10. Save the TCL file with same name as trace and nam file with .tcl extension
11. Go the terminal and type command : “ns filename.tcl”
12. Run trace file and check the movement of packet from source to destination.
13. To measure the performance of the experiment we create AWK file.
14. To create AWK file goto menu->accessories-> gedit.
15. Type the awk code and save in the same location.
16. To execute awk file goto terminal and type command awk –f filename.awk filename.tr

Analyzing the trace file

1. Trace file format for wired scenario

Event Time Where To Pkt Pkt Flags Flow Src Dest Seq Pkt id
from node type size id addr addr no
node

Trace file Event

Event Meaning
+ Added to queue
- Removed from queue
r Received at node
d Dropped

2. Trace file format for wireless scenario

Action Time Where Layer Flags Seq Type Size flags


from no
node

1. Action s – sent
r – Rxd
D - dropped
2. Time : when the action happened

3. From node : The node where action happened

4. Layer

AGT -> Application layer ( Application)

RTR – Network Layer (Routing)

LL – Link layer ( ARP is done here)

IFQ – Outgoing packet queue(between link & MAC layer)

MAC –

Dept. of TCE Page 6


Computer Communication Networks Lab 17TEL77 2020

Phy – Physical

5. Flags :

6. Seq no : the sequence number of the packet

7. Type : Packet type

Cbr -> CBR data stream pkt

DSR -> DSR routing pkt

RTS -> RTS pkt generated by MAC 802.11

APR -> Link layer ARP Packet

8. Size : The size of pkt at current layer, when pkt goes dwon, size

[ a b c d] : a -> pkt duration in MAC layer header

b -> The MAC address of destination

c -> The MAC address of source

d -> The MAC type of the pkt body

9. Flags :

Source node Port no of Port no ip ip of next hop


I/P Dest node i/p Header ttl (0 means node 0 or
(-1 Means broadcast) broadcast)

Dept. of TCE Page 7


Computer Communication Networks Lab 17TEL77 2020

Program 1

 Simulate a Point to Point Network with Four Nodes and Duplex Links between
them. Analyze the Network Performance by Setting the Queue Size and Varying
the Bandwidth.

AIM: To simulate a Point to Point Network with Four Nodes and Duplex Links between
them. Analyze the Network Performance by Setting the Queue Size and Varying the
Bandwidth.

set val(stop) 10.0 ;# time of simulation end


#Create a ns simulator
set ns [new Simulator]
#Open the NS trace file
set tracefile [open lab1.tr w]
$ns trace-all $tracefile
#Open the NAM trace file
set namfile [open lab1.nam w]
$ns namtrace-all $namfile
#Create 4 nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
$ns color 1 "blue"
$ns color 2 "red"
$ns at 0.0 "$n0 color blue"
$ns at 0.0 "$n1 color red"
$ns at 0.0 "$n0 label Source/Tcp0"

Dept. of TCE Page 8


Computer Communication Networks Lab 17TEL77 2020

$ns at 0.0 "$n1 label Source/Tcp1"


$ns at 0.0 "$n2 label Router"
$ns at 0.0 "$n3 label Destination"
$n0 shape hexagon
$n1 shape hexagon
$n3 shape square
#Createlinks between nodes
$ns duplex-link $n0 $n2 100.0Mb 20ms DropTail
$ns queue-limit $n0 $n2 20 #Q1
$ns duplex-link $n1 $n2 100.0Mb 20ms DropTail
$ns queue-limit $n1 $n2 20 #Q2
$ns duplex-link $n2 $n3 100.0Mb 20ms DropTail
$ns queue-limit $n2 $n3 20 #Q3
#Above Highlighted Bandwidth and Queue Size will be changed
#Give node position (for NAM)
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right
#Setup a TCP connection
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set sink2 [new Agent/TCPSink]
$ns attach-agent $n3 $sink2
$ns connect $tcp0 $sink2
$tcp0 set packetSize_ 1500
#Setup a TCP connection
set tcp1 [new Agent/TCP]
$ns attach-agent $n1 $tcp1
set sink3 [new Agent/TCPSink]
$ns attach-agent $n3 $sink3
$ns connect $tcp1 $sink3
$tcp1 set packetSize_ 1500
#Setup a FTP Application over TCP connection
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
$ns at 1.0 "$ftp0 start"
$ns at 8.0 "$ftp0 stop"
#Setup a FTP Application over TCP connection
set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
$ns at 1.0 "$ftp1 start"
$ns at 8.0 "$ftp1 stop"
#Define a 'finish' procedure
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam lab1.nam &
exit 0

Dept. of TCE Page 9


Computer Communication Networks Lab 17TEL77 2020

}
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
$ns run

Awk Script:
BEGIN{
tcppack=0
tcppack1=0
}
{
if($1=="r"&&$4=="3"&&$5=="tcp"&&$6=="1540")
{
tcppack++;
}
if($1=="d"&&$3=="2"&&$5=="tcp"&&$6=="1540")
{
tcppack1++;
}
}
END{
printf("\n total number of data packets received at Node 3: %d\n", tcppack++);
printf("\n total number of packets dropped at Node 2: %d\n", tcppack1++);
}

Network Animation (lab1.nam):

Dept. of TCE Page 10


Computer Communication Networks Lab 17TEL77 2020

Program 2

2. Simulate Ethernet LAN using n(6-10) Nodes and Assign Multiple traffic to the Nodes to
obtain
i. Congestion Window for different Sources/ Destinations.
ii. Compare the Throughput by changing the Error Rate and Data Rate.

i. Congestion Window for different Sources/ Destinations.


AIM: To simulate Congestion Window for different Sources/ Destinations.

set ns [new Simulator]


set tf [open lab4.tr w]
$ns trace-all $tf
set nf [open lab4.nam w]
$ns namtrace-all $nf
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
$ns make-lan "$n0 $n1 $n2 $n3" 10mb 10ms LL Queue/DropTail Mac/802_3
$ns color 1 "blue"
$ns color 2 "red"
$ns at 0.0 "$n3 color blue"
$ns at 0.0 "$n1 color red"
$ns at 0.0 "$n0 label Source/Tcp0"
$ns at 0.0 "$n2 label Source/Tcp2"
$ns at 0.0 "$n1 label Destination/Sink1"
$ns at 0.0 "$n3 label Destination/Sink3"
$n0 shape hexagon
$n2 shape hexagon
$n1 shape square
$n3 shape square
set tcp0 [new Agent/TCP/Reno]
$ns attach-agent $n0 $tcp0
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
set sink3 [new Agent/TCPSink]
$ns attach-agent $n3 $sink3

Dept. of TCE Page 11


Computer Communication Networks Lab 17TEL77 2020

$ns connect $tcp0 $sink3


set tcp2 [new Agent/TCP]
$ns attach-agent $n2 $tcp2
set ftp2 [new Application/FTP]
$ftp2 attach-agent $tcp2
set sink1 [new Agent/TCPSink]
$ns attach-agent $n1 $sink1
$ns connect $tcp2 $sink1
$tcp0 set class_ 1
$tcp2 set class_ 2
######To trace the congestion window##########
set file1 [open file1.tr w]
$tcp0 attach $file1
$tcp0 trace cwnd_
#$tcp0 set maxcwnd_ 10
set file2 [open file2.tr w]
$tcp2 attach $file2
$tcp2 trace cwnd_
proc finish { } {
global nf tf ns
$ns flush-trace
exec nam lab4.nam &
close $nf
close $tf
exit 0
}
$ns at 0.1 "$ftp0 start"
$ns at 1.5 "$ftp0 stop"
$ns at 2 "$ftp0 start"
$ns at 3 "$ftp0 stop"
$ns at 0.2 "$ftp2 start"
$ns at 2 "$ftp2 stop"
$ns at 2.5 "$ftp2 start"
$ns at 4 "$ftp2 stop"
$ns at 5.0 "finish"
$ns run

1. File1.tr is the Congestion Window (CWND) value of TCP agent.


2. File2.tr is the Congestion Window (CWND) value of TCPReno agent

Table 1: Above values are taken from file1.tr and file2.tr

Time TCP TCPReno


0.5 23.02 21.91
1 29.73 29.53
1.5 34.59 34.71
2 2 41.11
2.5 26.23 2
3 32.84 24.62
Dept. of TCE Page 12
Computer Communication Networks Lab 17TEL77 2020

Network Animation:

ii) Compare the Throughput by changing the Error Rate and Data Rate.

AIM: Compare the Throughput by changing the Error Rate and Data Rate.

set ns [new Simulator]


set tf [open lab3.tr w]
$ns trace-all $tf
set nf [open lab3.nam w]
$ns namtrace-all $nf
$ns color 0 blue
set n0 [$ns node]
$n0 color "red"

Dept. of TCE Page 13


Computer Communication Networks Lab 17TEL77 2020

set n1 [$ns node]


$n1 color "red"
set n2 [$ns node]
$n2 color "red"
set n3 [$ns node]
$n3 color "red"
set n4 [$ns node]
$n4 color "magenta"
set n5 [$ns node]
$n5 color "magenta"
set n6 [$ns node]
$n6 color "magenta"
set n7 [$ns node]
$n7 color "magenta"
$n1 label "Source/UDP"
$n3 label "Error Node"
$n7 label "Destination/Null"

$ns make-lan "$n0 $n1 $n2 $n3" 100Mb 300ms LL Queue/DropTail Mac/802_3
$ns make-lan "$n4 $n5 $n6 $n7" 100Mb 300ms LL Queue/DropTail Mac/802_3

$ns duplex-link $n3 $n4 100Mb 300ms DropTail


$ns duplex-link-op $n3 $n4 color "green"

# set error rate. Here ErrorModel is a class and it is single word and space should not be given
between Error and Model
# lossmodel is a command and it is single word. Space should not be given between loss and
model

set err [new ErrorModel]


$ns lossmodel $err $n3 $n4
$err set rate_ 0.1 #Change the Error Rate 0.1, 0.3, 0.5,
# error rate should be changed for each output like 0.1,0.3,0.5…. */
set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set fid_ 0
$cbr set packetSize_ 1000
$cbr set interval_ 0.001 #Change the Data Rate 0.001, 0.01, 0.1,
set null [new Agent/Null]
$ns attach-agent $n7 $null
$ns connect $udp $null
proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam lab3.nam &

Dept. of TCE Page 14


Computer Communication Networks Lab 17TEL77 2020

exit 0
}
$ns at 0.1 "$cbr start"
$ns at 3.0 "finish"
$ns run

Awk Script:
BEGIN{
tcppack=0
tcppack1=0
}
{
if($1=="r"&&$4=="7"&&$5=="cbr"&&$6=="1000")
{
tcppack++;
}
}
END{
printf("\n total number of data packets at Node 7: %d\n", tcppack++);
}

Results:
Error Rate Data Rate Received at Node 7
0.1 0.001 1255
0.3 0.01 95
0.5 0.1 05

Network Animation):

Dept. of TCE Page 15


Computer Communication Networks Lab 17TEL77 2020

Program 3

3. Simulate the Transmission of Ping Messages over a Network Topology consisting of Six
Nodes and Find the Number of Packets dropped due to Congestion.

AIM: To simulate transmission of Ping Messages over a Network Topology consisting of


Six Nodes and Find the Number of Packets dropped due to Congestion.

#Create a ns simulator
set ns [new Simulator]
#Open the NS trace file
set tracefile [open out.tr w]
$ns trace-all $tracefile
#Open the NAM trace file
set namfile [open out.nam w]
$ns namtrace-all $namfile
#Create 6 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]
#Createlinks between nodes
$ns duplex-link $n0 $n2 1.0Mb 10ms DropTail
$ns queue-limit $n0 $n2 50
$ns duplex-link $n1 $n2 1.0Mb 10ms DropTail
$ns queue-limit $n1 $n2 50
$ns duplex-link $n2 $n3 1.0Mb 10ms DropTail
$ns queue-limit $n2 $n3 50
$ns duplex-link $n3 $n4 1.0Mb 10ms DropTail
$ns queue-limit $n3 $n4 50
$ns duplex-link $n3 $n5 1.0Mb 10ms DropTail
$ns queue-limit $n3 $n5 50
#Give node position (for NAM)
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link-op $n3 $n4 orient right-up
$ns duplex-link-op $n3 $n5 orient right-down

#Define a 'recv' function for the class 'Agent/Ping'


Agent/Ping instproc recv {from rtt} {
$self instvar node_
puts "node [$node_ id] received ping answer from \
#$from with round-trip-time $rtt ms."
}

#Create two ping agents and attach them to the nodes n0 and n2
set p0 [new Agent/Ping]

Dept. of TCE Page 16


Computer Communication Networks Lab 17TEL77 2020

$ns attach-agent $n0 $p0

set p1 [new Agent/Ping]


$ns attach-agent $n1 $p1

set p2 [new Agent/Ping]


$ns attach-agent $n4 $p2

set p3 [new Agent/Ping]


$ns attach-agent $n5 $p3

#Connect the two agents


$ns connect $p0 $p2
$ns connect $p1 $p3

#Schedule events
$ns at 0.2 "$p0 send"
$ns at 0.4 "$p1 send"

$ns at 0.6 "$p2 send"


$ns at 0.8 "$p3 send"

$ns at 1.0 "finish"

#Define a 'finish' procedure


proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam out.nam &
exit 0
}
$ns run

Awk Script
BEGIN{
a=0
b=0
}
{
if($1=="r")
{
a++;
}
if($1=="d")
{
b++;
}
}

Dept. of TCE Page 17


Computer Communication Networks Lab 17TEL77 2020

END{
printf("\n total number of packets received packet: %d\n", a++);
printf("\n total number of packets Dropped Packets: %d\n", b++);
}

Network Animation:

Dept. of TCE Page 18


Computer Communication Networks Lab 17TEL77 2020

Program 4

4. Simulate a Simple BSS with Transmitting Nodes in Wireless LAN and Determine
the Performance with respect to Transmission of Packets.

AIM: To simulate Simple BSS with Transmitting Nodes in Wireless LAN and Determine the
Performance with respect to Transmission of Packets.

set val(chan) Channel/WirelessChannel ;# channel type


set val(prop) Propagation/TwoRayGround ;# radio-propagation model
set val(netif) Phy/WirelessPhy ;# network interface type
set val(mac) Mac/802_11 ;# MAC type
set val(ifq) Queue/DropTail/PriQueue ;# interface queue type
set val(ll) LL ;# link layer type
set val(ant) Antenna/OmniAntenna ;# antenna model
set val(ifqlen) 50 ;# max packet in ifq
set val(nn) 4 ;# number of mobilenodes
set val(rp) AODV ;# routing protocol
set val(x) 959 ;# X dimension of topography
set val(y) 834 ;# Y dimension of topography
set val(stop) 10.0 ;# time of simulation end

#Create a ns simulator
set ns [new Simulator]

#Setup topography object


set topo [new Topography]
$topo load_flatgrid $val(x) $val(y)
create-god $val(nn)

#Open the NS trace file


set tracefile [open out.tr w]
$ns trace-all $tracefile

#Open the NAM trace file


set namfile [open out.nam w]
$ns namtrace-all $namfile
$ns namtrace-all-wireless $namfile $val(x) $val(y)
set chan [new $val(chan)];#Create wireless channel

$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) \
-channel $chan \
-topoInstance $topo \

Dept. of TCE Page 19


Computer Communication Networks Lab 17TEL77 2020

-agentTrace ON \
-routerTrace ON \
-macTrace ON \
-movementTrace ON
#Create 4 nodes
set n0 [$ns node]
$n0 set X_ 618
$n0 set Y_ 734
$n0 set Z_ 0.0
$ns initial_node_pos $n0 20
set n1 [$ns node]
$n1 set X_ 374
$n1 set Y_ 711
$n1 set Z_ 0.0
$ns initial_node_pos $n1 20
set n2 [$ns node]
$n2 set X_ 633
$n2 set Y_ 506
$n2 set Z_ 0.0
$ns initial_node_pos $n2 20
set n3 [$ns node]
$n3 set X_ 859
$n3 set Y_ 683
$n3 set Z_ 0.0
$ns initial_node_pos $n3 20
#Setup a TCP connection
set tcp0 [new Agent/TCP]
$ns attach-agent $n1 $tcp0
set sink1 [new Agent/TCPSink]
$ns attach-agent $n3 $sink1
$ns connect $tcp0 $sink1
$tcp0 set packetSize_ 1500
#Setup a FTP Application over TCP connection
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
$ns at 1.0 "$ftp0 start"
$ns at 8.0 "$ftp0 stop"
#Define a 'finish' procedure
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam out.nam &
exit 0
}
for {set i 0} {$i < $val(nn) } { incr i } {
$ns at $val(stop) "\$n$i reset"
}
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"

Dept. of TCE Page 20


Computer Communication Networks Lab 17TEL77 2020

$ns at $val(stop) "finish"


$ns at $val(stop) "puts \"done\" ; $ns halt"
$ns run

Awk Script

BEGIN{
cbrpack=0
cbrpack1=0
cbrpack2=0
}
{
if($1=="r"&&$3=="_3_"&&$4=="AGT"&&$7=="tcp"&&$8=="1540")
{
cbrpack++;
}
if($1=="s"&&$3=="_1_"&&$4=="AGT"&&$7=="tcp"&&$8=="1540")
{
cbrpack1++;
}
if($1=="D"&&$3=="_0_"&&$4=="AGT"&&$7=="tcp"&&$8=="1540")
{
cbrpack2++;
}
}
END{
printf("\n total number of packets drop: %d\n", cbrpack2++);
printf("\n total number of packets sent: %d\n", cbrpack1++);
printf("\n total number of packets received: %d\n", cbrpack++);
}
Network Animation:

Dept. of TCE Page 21


Computer Communication Networks Lab 17TEL77 2020

Program 5

5. Build a Four-node Point to Point Network with links n0-n2, n1-n2 and n2-n3. Connect
a TCP link between n0-n3 and UDP link between n1-n3.
(i) Define BERs for Links. Compare TCP and UDP Protocols when errors occur.
(ii) Modify to Simulate a Link Failure between the Host and the Target Node. Compare
TCP and UDP Protocols when the Target Node is not accessible.

(i) Define BERs for Links. Compare TCP and UDP Protocols when errors occur.

AIM: To simulate a Four-node Point to Point Network with links n0-n2, n1-n2 and n2-n3. And
define BERs for Links. Compare TCP and UDP Protocols when errors occur.

set val(stop) 50.0 ;# time of simulation end


#Create a ns simulator
set ns [new Simulator]

#Open the NS trace file


set tracefile [open out.tr w]
$ns trace-all $tracefile
#Open the NAM trace file
set namfile [open out.nam w]
$ns namtrace-all $namfile
#Create 4 nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
#Createlinks between nodes
$ns duplex-link $n0 $n2 100.0Mb 10ms DropTail
$ns queue-limit $n0 $n2 50
$ns duplex-link $n1 $n2 100.0Mb 10ms DropTail
$ns queue-limit $n1 $n2 50
$ns duplex-link $n2 $n3 100.0Mb 10ms DropTail
$ns queue-limit $n2 $n3 50
#Give node position (for NAM)
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right
#set err [new ErrorModel]
#$ns lossmodel $err $n2 $n3
#$err set rate_ 0.1
#Setup a TCP connection
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set sink2 [new Agent/TCPSink]
$ns attach-agent $n3 $sink2
$ns connect $tcp0 $sink2
$tcp0 set packetSize_ 1500
#Setup a UDP connection

Dept. of TCE Page 22


Computer Communication Networks Lab 17TEL77 2020

set udp1 [new Agent/UDP]


$ns attach-agent $n1 $udp1
set null3 [new Agent/Null]
$ns attach-agent $n3 $null3
$ns connect $udp1 $null3
$udp1 set packetSize_ 1500
#Setup a FTP Application over TCP connection
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
$ns at 1.0 "$ftp0 start"
$ns at 20.0 "$ftp0 stop"
#Setup a CBR Application over UDP connection
set cbr1 [new Application/Traffic/CBR]
$cbr1 attach-agent $udp1
$cbr1 set packetSize_ 1000
$cbr1 set rate_ 1.0Mb
$cbr1 set random_ null
$ns at 25.0 "$cbr1 start"
$ns at 48.0 "$cbr1 stop"

#Define a 'finish' procedure


proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam out.nam &
exit 0
}
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
$ns run

Awk Script

BEGIN{
a=0
b=0
}
{
if($1=="r"&&$4=="3"&&$5=="tcp"&&$6=="1540")
{
a++;
}
if($1=="r"&&$4=="3"&&$5=="cbr"&&$6=="1000")
{
b++;
}
}

Dept. of TCE Page 23


Computer Communication Networks Lab 17TEL77 2020

END{
printf("\n total number of packets received at tcp: %d\n", a++);
printf("\n total number of packets received at udp: %d\n", b++);
}

Network Animation:

(ii) Modify to Simulate a Link Failure between the Host and the Target Node. Compare
TCP and UDP Protocols when the Target Node is not accessible.

AIM: To simulate a Four-node Point to Point Network with links n0-n2, n1-n2 and n2-n3. and
modify to Simulate a Link Failure between the Host and the Target Node. Compare TCP and
UDP Protocols when the Target Node is not accessible.

set val(stop) 50.0 ;# time of simulation end


#Create a ns simulator
set ns [new Simulator]

#Open the NS trace file


set tracefile [open out.tr w]
$ns trace-all $tracefile
#Open the NAM trace file
set namfile [open out.nam w]
$ns namtrace-all $namfile
#Create 4 nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
#Createlinks between nodes
$ns duplex-link $n0 $n2 100.0Mb 10ms DropTail

Dept. of TCE Page 24


Computer Communication Networks Lab 17TEL77 2020

$ns queue-limit $n0 $n2 50


$ns duplex-link $n1 $n2 100.0Mb 10ms DropTail
$ns queue-limit $n1 $n2 50
$ns duplex-link $n2 $n3 100.0Mb 10ms DropTail
$ns queue-limit $n2 $n3 50
#Give node position (for NAM)
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns duplex-link-op $n2 $n3 orient right
#set err [new ErrorModel]
#$ns lossmodel $err $n2 $n3
#$err set rate_ 0.1
#Setup a TCP connection
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set sink2 [new Agent/TCPSink]
$ns attach-agent $n3 $sink2
$ns connect $tcp0 $sink2
$tcp0 set packetSize_ 1500
#Setup a UDP connection
set udp1 [new Agent/UDP]
$ns attach-agent $n1 $udp1
set null3 [new Agent/Null]
$ns attach-agent $n3 $null3
$ns connect $udp1 $null3
$udp1 set packetSize_ 1500
#Setup a FTP Application over TCP connection
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
$ns at 1.0 "$ftp0 start"
$ns at 20.0 "$ftp0 stop"
#Setup a CBR Application over UDP connection
set cbr1 [new Application/Traffic/CBR]
$cbr1 attach-agent $udp1
$cbr1 set packetSize_ 1000
$cbr1 set rate_ 1.0Mb
$cbr1 set random_ null
$ns at 25.0 "$cbr1 start"
$ns at 48.0 "$cbr1 stop"

#$ns at 10.0 "$ns detach-agent $n0 $tcp0 ; $ns detach-agent $n3 $sink2"
#$ns at 30.0 "$ns detach-agent $n0 $udp1 ; $ns detach-agent $n3 $null3"

#Define a 'finish' procedure


proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam out.nam &

Dept. of TCE Page 25


Computer Communication Networks Lab 17TEL77 2020

exit 0
}
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
$ns run

Awk Script

BEGIN{
a=0
b=0
}
{
if($1=="r"&&$4=="3"&&$5=="tcp"&&$6=="1540")
{
a++;
}
if($1=="r"&&$4=="3"&&$5=="cbr"&&$6=="1000")
{
b++;
}
}
END{
printf("\n total number of packets received at tcp: %d\n", a++);
printf("\n total number of packets received at udp: %d\n", b++);
}
Network Animation:

Dept. of TCE Page 26


Computer Communication Networks Lab 17TEL77 2020

Program 6

5. Simulate a Network with a Star Topology (One Router and several Hosts). Declare
Applications (TCP or UDP) to send Packets from Hosts and to receive (on one
Host). Test the Bandwidth and the Delay, when Buffers are of infinite Capacities
and Buffers are of Limited Capacities.

AIM: To simulate a network with Star Topology (One Router and several Hosts).
Declare Applications (TCP or UDP) to send Packets from Hosts and to receive (on one
Host). Test the Bandwidth and the Delay, when Buffers are of infinite Capacities and
Buffers are of Limited Capacities.

set val(stop) 10.0 ;# time of simulation end


#Create a ns simulator
set ns [new Simulator]

#Open the NS trace file


set tracefile [open out.tr w]
$ns trace-all $tracefile

#Open the NAM trace file


set namfile [open out.nam w]
$ns namtrace-all $namfile

#Create 5 nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]

#Createlinks between nodes


$ns duplex-link $n0 $n3 100.0Mb 10ms DropTail
$ns queue-limit $n0 $n3 5
$ns duplex-link $n1 $n3 100.0Mb 10ms DropTail
$ns queue-limit $n1 $n3 5
$ns duplex-link $n2 $n3 100.0Mb 10ms DropTail
$ns queue-limit $n2 $n3 5
$ns duplex-link $n3 $n4 100.0Mb 10ms DropTail
$ns queue-limit $n3 $n4 5
#Give node position (for NAM)
$ns duplex-link-op $n0 $n3 orient right-down
$ns duplex-link-op $n1 $n3 orient right-up
$ns duplex-link-op $n2 $n3 orient left-up
$ns duplex-link-op $n3 $n4 orient right-up

#Setup a TCP connection


set tcp0 [new Agent/TCPz
$ns attach-agent $n0 $tcp0

Dept. of TCE Page 27


Computer Communication Networks Lab 17TEL77 2020

set sink3 [new Agent/TCPSink]


$ns attach-agent $n4 $sink3
$ns connect $tcp0 $sink3
$tcp0 set packetSize_ 1500
#Setup a TCP connection
set tcp1 [new Agent/TCP]
$ns attach-agent $n1 $tcp1
set sink4 [new Agent/TCPSink]
$ns attach-agent $n4 $sink4
$ns connect $tcp1 $sink4
$tcp1 set packetSize_ 1500

#Setup a TCP connection


set tcp2 [new Agent/TCP]
$ns attach-agent $n2 $tcp2
set sink5 [new Agent/TCPSink]
$ns attach-agent $n4 $sink5
$ns connect $tcp2 $sink5
$tcp2 set packetSize_ 1500

#Setup a FTP Application over TCP connection


set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
$ns at 1.0 "$ftp0 start"
$ns at 2.0 "$ftp0 stop"

#Setup a FTP Application over TCP connection


set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
$ns at 2.0 "$ftp1 start"
$ns at 3.0 "$ftp1 stop"

#Setup a FTP Application over TCP connection


set ftp2 [new Application/FTP]
$ftp2 attach-agent $tcp2
$ns at 3.0 "$ftp2 start"
$ns at 4.0 "$ftp2 stop"

#Define a 'finish' procedure


proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam out.nam &
exit 0
}
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"

Dept. of TCE Page 28


Computer Communication Networks Lab 17TEL77 2020

$ns run

Awk Script

BEGIN{
a=0
b=0
}
{
if($1=="r"&&$4=="4"&&$5=="tcp"&&$6=="1540")
{
a++;
}
}
END{
printf("\n total number of packets received at tcp: %d\n", a++);
}

Network Animation:

Dept. of TCE Page 29


Computer Communication Networks Lab 17TEL77 2020

Program 7

7. Implementation of Link State Routing Algorithm.

AIM: To simulate Link State Routing Algorithm.

set val(stop) 10.0 ;# time of simulation end


#Create a ns simulator
set ns [new Simulator]
#Open the NS trace file
set tracefile [open lab6.tr w]
$ns trace-all $tracefile
#Open the NAM trace file
set namfile [open lab6.nam w]
$ns namtrace-all $namfile
#Create 5 nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
#Createlinks between nodes
$ns duplex-link $n0 $n1 100.0Mb 10ms DropTail
$ns queue-limit $n0 $n1 50
$ns duplex-link $n0 $n2 100.0Mb 10ms DropTail
$ns queue-limit $n0 $n2 50
$ns duplex-link $n2 $n3 100.0Mb 10ms DropTail
$ns queue-limit $n2 $n3 50
$ns duplex-link $n1 $n3 100.0Mb 10ms DropTail
$ns queue-limit $n1 $n3 50
$ns duplex-link $n3 $n4 100.0Mb 10ms DropTail

Dept. of TCE Page 30


Computer Communication Networks Lab 17TEL77 2020

$ns queue-limit $n3 $n4 50


$ns duplex-link $n0 $n3 100.0Mb 10ms DropTail
$ns queue-limit $n0 $n3 50
$ns duplex-link $n1 $n2 100.0Mb 10ms DropTail
$ns queue-limit $n1 $n2 50

#Give node position (for NAM)


$ns duplex-link-op $n0 $n1 orient right
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n2 $n3 orient right
$ns duplex-link-op $n1 $n3 orient left-down
$ns duplex-link-op $n3 $n4 orient left-down
$ns duplex-link-op $n0 $n3 orient right-down
$ns duplex-link-op $n1 $n2 orient left-down

#Set the link costs. All link costs are symmetric


$ns cost $n0 $n1 2
$ns cost $n0 $n2 1
$ns cost $n0 $n3 3
$ns cost $n1 $n0 2
$ns cost $n1 $n2 2
$ns cost $n1 $n3 3
$ns cost $n2 $n1 2
$ns cost $n2 $n0 1
$ns cost $n2 $n3 1
$ns cost $n3 $n2 1
$ns cost $n3 $n1 3
$ns cost $n3 $n0 3
$ns cost $n3 $n4 2
$ns cost $n4 $n3 2
#Setup a UDP connection
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
set null1 [new Agent/Null]
$ns attach-agent $n4 $null1
$ns connect $udp0 $null1
$udp0 set packetSize_ 1500
#Setup a CBR Application over UDP connection
set cbr0 [new Application/Traffic/CBR]
$cbr0 attach-agent $udp0
$cbr0 set packetSize_ 1000
$cbr0 set rate_ 1.0Mb
$cbr0 set random_ null
$ns at 1.0 "$cbr0 start"

Dept. of TCE Page 31


Computer Communication Networks Lab 17TEL77 2020

$ns at 5.0 "$cbr0 stop"


$ns rtproto LS
#Define a 'finish' procedure
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam lab6.nam &
exit 0
}
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
$ns run

Network Animation :

 Total Number of Routing Paths: 4


1. N0-N1-N2-N3-N4: Total Cost is of 7
2. N0-N2- N1 -N3-N4 : Total Cost is of 8
3. N0-N2-N3-N4 : Total Cost is of 4
4. N0-N3-N4 : Total Cost is of 5

 Shortest according to Link State algorithm is N0-N2-N3-N4 having Total Cost is of 4

Dept. of TCE Page 32


Computer Communication Networks Lab 17TEL77 2020

Dept. of TCE Page 33


Computer Communication Networks Lab 17TEL77 2020

PART B

Experiments conducted using C/C++


Code::Blocks
It is a free, open-source cross-platform IDE that supports multiple compilers including GCC,
Clang and Visual C++. It is developed in C++ using wx Widgets as the GUI toolkit. Using a
plug in architecture, its capabilities and features are defined by the provided plugins. Currently,
Code::Blocks is oriented towards C, C++, and Fortran. It has a custom build system and
optional Make support.

Code::Blocks is being developed for Windows, Linux, and macOS and has been ported to
FreeBSD,[2] OpenBSD[3] and Solaris.

Features of code block are: Compilers

Code::Blocks supports multiple compilers, including GCC, MinGW, Digital Mars, Microsoft
Visual C++, Borland C++, LLVM Clang, Watcom, LCC and the Intel C++ compiler. Although
the IDE was designed for the C++ language, there is some support for other languages,
including Fortran and D. A plug-in system is included to support other programming languages.

Code editor

The IDE features syntax highlighting and code folding (through its Scintilla editor component),
C++ code completion, class browser, a hex editor and many other utilities. Opened files are
organized into tabs. The code editor supports font and font size selection and personalized
syntax highlighting colors.

Debugger

The Code::Blocks debugger has full breakpoint support. It also allows the user to debug their
program by having access to the local function symbol and argument display, user-defined
watches, call stack, disassembly, custom memory dump, thread switching, CPU registers and
GNU Debugger Interface.

GUI designer

As of version 13.12 Code::Blocks comes with a GUI designer called wxSmith. It is a derivative
port of wxWidgets version 2.9.4. To make a complete wxWidgets application, the appropriate
wxWidgets SDK must be installed.

User migration

Some of Code::Blocks features are targeted at users migrating from other IDE's - these include
Dev-C++, Microsoft Visual C++ project import (MSVC 7 & 10), and Dev-C++ Devpak
support.

Dept. of TCE Page 34


Computer Communication Networks Lab 17TEL77 2020

P Code::Blocks uses a custom build system, which stores its information in XML-based project
files. It can optionally use external make files, which simplifies interfacing with projects using
the GNU or q make build systems.

Program Execution Procedure on Linux


 Right click the mouse to find a drop down list, from which select new document
 Type the program in C/C++
 Save the program using save options with .c/.cpp extension
 Right click the mouse to find a drop down list, from which select open terminal
 To compile use the command g++ filename.cpp –o object_filename
 For any errors use gedit editor to rectify the errors
 To execute use the command ./object_filename

Dept. of TCE Page 35


Computer Communication Networks Lab 17TEL77 2020

Program 1
1. Write a Program for asynchronous communication (Example: File Transfer)
between PCs using RS232 Cable.

Aim: To simulate asynchronous communication between PCs using RS232 Cable.

Procedure:

ASYNCHRONOUS COMMUNICATION USING RS 232

1. Connect the RS232 cable between transmitter and receiver (bi directional).
2. Switch on power supply and reset both transmitter and receiver.
3. At the transmitter:
a) Select
1) Parallel mode
2) Serial mode
b) Select
1) Asynchronous serial mode
2) Synchronous serial mode
c) Select
1) Asynchronous RS232 mode
2) Asynchronous twisted pair or fiber optic mode
d) Select
1) Local transmitter
2) Local receiver
3) PC
4) Local loop
4. At the receiver, repeat steps (a) to (d) and in (d) select local receiver i.e. option (2) and
press enter.
5. Now give data on transmitter side that has to be transmitted and press enter.
6. Now at receiver, data is received and it‟s the same as data entered at the transmitter.

SYNCHRONOUS COMMUNICATION USING RS 232

1. Connect the RS232 cable between transmitter and receiver (bi directional).
2. Switch on power supply and reset both transmitter and receiver.
3. At the transmitter:
a) Select
i. Parallel mode
ii. Serial mode
b) Select
i. Asynchronous serial mode
ii. Synchronous serial mode
c) Select

Dept. of TCE Page 36


Computer Communication Networks Lab 17TEL77 2020

i. Asynchronous RS232 mode


ii. Asynchronous twisted pair or fiber optic mode
d) Select
i. Local transmitter
ii. Local receiver
iii. PC
iv. Local loop
4. At the receiver, repeat steps (a) to (d) and in (d) select local receiver i.e. option (2) and
press enter.
5. Now give data on transmitter side that has to be transmitted and press enter.
6. Now at receiver, data is received and it‟s the same as data entered at the transmitter

RS 232 Cable Pin Diagram

Program
#include<stdio.h>
#include<conio.h>
#include<bios.h>
#define SETTINGS (_COM_9600 |_COM_CHR8)
|_COM_NOPARIT|_COM_STOP1)

/* baud rate = 9600, 8 data bits, no parity bit, 1stpo bit */


Void main(void)
{
Unsigned in,out,status;
Int port=0;

Dept. of TCE Page 37


Computer Communication Networks Lab 17TEL77 2020

Clrscr();
{
Cprintf(“\n\rData Received:”);
_bios_serialcom(_COM_INIT,port,SETTINGS);
for(;;)
{
If(kbhit())/* if a keystroke is currently available*/

{
In=getch();/*get a character without echoing onto the screen */
If(in==27)/*if ESC*/
Break;
_bios_serialcom(_COM_SEND,port,in);
}

Status=__bios_serialcom(_COM_STATUS,port,0);
If(status & 256) /* if data ready */
{
If((out= _bios_serialcom(_COM_REACEIVE,port,0) & 255)!=0)
Putch(out);
}

}
}

Output :

Enter the input from any of the PC‟s get the output in other PC.

Dept. of TCE Page 38


Computer Communication Networks Lab 17TEL77 2020

Program 2

2. Write a program for a HLDC frame to perform the following


(i) Bit stuffing
(ii) Character stuffing
(i) Bit Stuffing

Aim: To simulate bit stuffing using C++.

Theory:
The new technique allows data frames to contain an arbitrary number if bits and allows
character codes with an a arbitrary no of bits per character. Each frame beings and ends with
special bit pattern, 01111110, called a flog byte. Whenever the sender‟s data link layer
encounters five consecutive ones in the data, it automatically stuffs 0 bit into the outgoing bit
stream

HDLC Frame format

Flag Address Control Information FCS Flag

a) Flag Field
Flag field of an HDLC Frame Is an 8 bit sequence with a bit pattern 0111 1110 that
identifies both the beginning and end of a frame.

b) Address Field
It contains address of the secondary station (i.e)

 If a primary station creates a frame it contain to address


 If a secondary station creates a frame it contains a from address.
 Address field can be 1 byte or several byte long depending on the needs of the network.
i.e and byte long can identify upto 128 stations,

c) Control Field
 It is 1 or 2 Byte segment of the frame used for flow and error control

d) Information field
 It contains user‟s data from the network layer the length can vary from one n/w to
another.

e) FCS field – frame check sequence


 It is a error detection field
 It contains either a 2 or 4 byte ITU-T CRC

Dept. of TCE Page 39


Computer Communication Networks Lab 17TEL77 2020

Algorithm : 1

Step 1 : Initialize the array of data a[i[ & count =0

Step 2 : Enter the data

Step 3 : Check the number of 1‟s in the data if found increment the count by 1

Step 4 : Repeat step 3 till the complete length of the data.

Step 5 : If count = 5, then pad the next bit of the array by a zero

Step 6 : Print the stuffed data

#include <iostream>
#include<conio.h>
#include<stdio.h>
using namespace std;

int main()
{
char ch,a[20];
int count=0, i=0,j=0;
cout << " enter data" << endl;
while((ch=getche())!='\r')

{
if(ch=='1')
++count;
else
count=0;
a[i++]=ch;

if(count==5)
{
a[i++]='0';
count=0;
Dept. of TCE Page 40
Computer Communication Networks Lab 17TEL77 2020

}
}
cout<< "\n stuffed data is:";
for(j=0;j<i;++j)
{
cout<<a[j];
}

getch();
}

Output :

(ii) Character Stuffing

Aim: To simulate character stuffing using C++ language.

Theory:
The framing method gets around the problem of resynchronization after an error by
having each frame start with the ASCII character sequence DLESTX and the sequence DLE
EXT. if the destination ever losses the track of the frame boundaries all it has to do is look for
DLESTX or DLEETX characters to figure it out. The data link layer on the receiving end
removes the DLE before the data are given to the network layer. This technique is called
character stuffing.

Algorithm

Step 1 : Initialize the array of data a[i[ to enter the string and array b[j] to print the stuffed
character. Include string.h header file

Dept. of TCE Page 41


Computer Communication Networks Lab 17TEL77 2020

Step 2 : Enter the string of data & find the length of the string

Step 3 : Stuff at the beginning “dlestx”

Step 4 : Check each character in data. If character „dle‟ is found consequently in the data then
stuff the data by „esc‟ before dle in the data.

Step 5 : Staff at the end of the data with characters “dleetx”

Step 6 : Print the stuffed data

Program
#include <iostream>
#include <stdio.h>
#include<string.h>
using namespace std;
int main()

{
int i=0,j=0,n,pos;
char a[20],b[50],ch;
cout<<"enter the string \n";
cin>>a;
n=strlen(a);

b[0]='d';
b[1]='l';
b[2]='e';
b[3]='s';
b[4]='t';
b[5]='x';
j=6;

while(i<n)
{
if(a[i]=='d'&&a[i+1]=='l'&&a[i+2]=='e')
{

Dept. of TCE Page 42


Computer Communication Networks Lab 17TEL77 2020

b[j]='d';
b[j+1]='1';
b[j+2]='e';
j=j+3;
}
b[j]=a[i];
i++;

j++;
}
b[j]='d';
b[j+1]='l';
b[j+2]='e';
b[j+3]='e';

b[j+4]='t';
b[j+5]='x';
b[j+6]='\0';
cout<<"\n frame after stuffing: \n";
cout<<b;
}

Output :

Dept. of TCE Page 43


Computer Communication Networks Lab 17TEL77 2020

Program 3

3. Write a Program to obtain CRC Code for the given data, using CRC-CCITT (
CRC 16 ) polynomial. Verify the program for the cases
i. Without error
ii. With error
Aim: To simulate CRC Code for the given data, using CRC-CCITT polynomial.

Theory:

A cyclic redundancy check (CRC) is an error-detecting code commonly used in digital


networks and storage devices to detect a accidental changes to raw data. Block of data entering
these systems get a short check value attached, based on the reminder of a polynomial division
of their contents; on retrieval the calculation is repeated, and corrective action can be taken
against presumed data corruption if the check values do not match.

Example:

To compute an n-bit binary CRC, line the bits representing the input in a raw, and position the
(n+1)-bit pattern representing the CRC‟s divisor (called a “polynomial”) underneath the left-
hand end of the

Row start with the message to be ended:

11010011101100

This is first padded with zeroes corresponding to the bit length n of the CRC. Here is the first
calculation for computing a 3-bit CRC:

11010011101100 000

 INPUT RIGHT PADDED WITH ZERO BITS 1011


 DIVISOR (4 BITS)
01100011101100 000

Result

If the input bit above the left most divisor bit is 0, do nothing. If the input bit above the leftmost
divisor bit is 1, the divisor is XORed into the input. Divisor is then shifted one bit to the right,
and the process is repeated until the divisor recharges the right-hand end of the input row. Here
is the entire calculation:

Dept. of TCE Page 44


Computer Communication Networks Lab 17TEL77 2020

Since the leftmost divisor bit zeroed every input bit it touched, when this process ends thr only
bits in the input row that can be non zero are the n bits at the right-hand end of the row. These n
bits are the reminder of the divisor step, and will also be the value of the CRC function (unless
the chosen CRC specification calls for some post processing).

The validity of a received message can easily be verified by performing the above calculation
again, this time with the check value added instead of zeroes. The reminder should equal zero if
there are detectable errors.

Dept. of TCE Page 45


Computer Communication Networks Lab 17TEL77 2020

Program
#include<iostream>
#include<stdio.h>
#include<conio.h>
#include<string.h>
using namespace std;
char t[28],cs[28],g[30];

int a,i,j,N;
void xor()
{
for(j=1; j<N; j++)
cs[j] = ((cs[j]==g[j])?'0':'1');
}

void crc()
{
for(i=0;i<N;i++)
cs[i]=t[i];
do
{

if(cs[0]=='1')
xor();
for(j=0;j<N-1;j++)
cs[j]=cs[j+1];
cs[j]=t[i++];
}while(i<=a+N-1);

}
int main()
{
cout<<"\n message to be send is :";

Dept. of TCE Page 46


Computer Communication Networks Lab 17TEL77 2020

cin>>t;
cout<<"\n-------------------";
cout<<"\nGenerating polynomial : ";
scanf("%s",&g);
a=strlen(t);
N=strlen(g);
for(i=a;i<(a+N-1);i++)

t[i]='0';
cout<<"\n after appending zero's to message :";
cout<<t;
cout<<"\n-------------------------------------";
crc();
cout<<"\n checksum is :"<<cs;

for(i=a;i<(a+N-1);i++)
t[i]=cs[i-a];
cout<<"\n-----------------------------------");
cout<<"\n final codeword(message + checksum)to be transmitted is :"<<t;
cout<<"\n-----------------------------");
cout<<"\n Enter received message");

cin>>t;
crc();
cout<<"\n REMAINDER : %s"<<cs;
for(i=0;(i<N-1)&&(cs[i]!='1');i++);
if(i<N-1)
cout<<"\n\n error detected\n\n";

else
cout<<"\n\n No error detected\n\n";
getch();
}

Dept. of TCE Page 47


Computer Communication Networks Lab 17TEL77 2020

Output :

Output without Error

Output with error

Dept. of TCE Page 48


Computer Communication Networks Lab 17TEL77 2020

Program 4

4. Write a Program for Simulation of Stop and Wait Protocol and Sliding Window
Protocol.
(i) Stop and Wait Protocol

Aim: To simulate Stop and Wait Protocol.

Theory:

Stop and wait protocol, uses both flow and error control. Both sender and the receive use a
sliding window of size 1. The sender sends one packet at a time and waits for an
acknowledgment before sending the next one. To detect corrupted packets, we need to add a
checksum to each data packet. When a packet arrives at the receiver and silently discarded. The
silence of the receiver is a single for the sender that a packet was either corrupted or lost. Every
time the sender sends a packet, it starts a timer. If an acknowledgment arrives before the timer
expires, the timer is stopped and the sender sends the next packet (if it has one to send), if the
timer expires, the sender resends the previous packet, assuming that the packet was either lost or
corrupted. This means that the sender needs to keep a copy of the packet until its
acknowledgment arrives.

Figure shows the outline for the stop-and-wait protocol. Note that only one packet and one
acknowledgment can be in the channels at any time.

Program
#include <iostream>

#include <time.h>
#include <stdio.h>
#include <windows.h>

Dept. of TCE Page 49


Computer Communication Networks Lab 17TEL77 2020

#include <conio.h>
#define RTT 4
#define TIMEOUT 4
#define TOT_FRAMES 7
enum {NO,YES} ACK;
using namespace std;
int main()

{
int wait_time,i=1;
ACK=YES;
for(;i<=TOT_FRAMES;)
{
if (ACK==YES && i!=1)

{
cout<<"\n SENDER: ACK for Frame " << i-1 << " Received \n ";
}
cout<<"\n SENDER: Frame "<< i << " sent, Waiting for ACK...\n";
ACK=NO;
wait_time= rand() % 4+1;

if (wait_time==TIMEOUT)
{
cout<<"\n SENDER: ACK not received for Frame "<< i <<" => TIMEOUT Resending
Frame... \n ";

}
else
{
Sleep(RTT/2);
cout<< "\n RECEIVER: Frame " << i <<" received, ACK sent \n ";
cout<< "\n --------------------------------------------\n ";
ACK=YES;

Dept. of TCE Page 50


Computer Communication Networks Lab 17TEL77 2020

Sleep(RTT/2);
i++;
}
}
return 0;
}

Output :

(ii) Sliding Window Protocol


Aim: To simulate Sliding Window Protocol

Theory:

In the Protocol (and the next), the sliding window is an abstract concept that defines the range
of sequence numbers that is the concern of the sender and receiver. In other words, the sender
and receiver need to deal with only part of the possible sequence numbers.

The range which is the concern of the sender is called the send sliding window; the range that is
the concern of the receiver is called the receive sliding window. We discuss both here. The send
window is an imaginary box covering the sequence numbers of the data frames which can be
transit.
In each window position, some of these sequence numbers define the frames that have been
sent;others define those that can be sent. The maximum size of the window is 2 m -1 for reasons

Dept. of TCE Page 51


Computer Communication Networks Lab 17TEL77 2020

that we discuss that we discuss later. In this chapter, we let the size be fixed and set to the
maximum value, but we will see in future chapters that some protocols may have a variable
window size.

Program
#include <iostream>
#include <stdio.h>
#include<conio.h>
#include <time.h>
#include <windows.h>
#define RTT 5
using namespace std;
int main()
{
int window_size,i,f,frames[50];
cout<<" \n Enter window size: ";
cin>>window_size;
cout<<"\n Enter number of frames to transmit: ";

cin>>f;
cout<<"\n Enter " << f << " frames \n";
for(i=1;i<=f;i++)
{

Dept. of TCE Page 52


Computer Communication Networks Lab 17TEL77 2020

cin>>frames[i];
}
cout<<"\n after sending " << window_size << " frames at each stage sender waits for ACK ";
cout<<"\n sending frames in the following manner .......\n\n";
for (i=1;i<=f;i++)
{
if(i%window_size!=0)

{
cout<<"\n"<<frames[i];
}
else
{
cout<<"\n"<<frames[i];

cout<<"\n SENDER: waiting for ACK.....\n\n";


Sleep(RTT/2);
cout<<"\n Reciver: frames Received, ACK sent \n";
cout<<"\n -------------------------------\n";
Sleep(RTT/2);
cout<<"\n SENDER: ACK received, sending next frames \n";

}
if(f%window_size!=0)
{
cout<<"\n SENDER: waiting for ACK........ \n";
Sleep(RTT/2);
cout<<"\n Receiver: Frames received, ACK sent\n";

cout<<"\n ---------------------------------------\n";
Sleep(RTT/2);
cout<<"\n SENDER: ACK received ";
}

Dept. of TCE Page 53


Computer Communication Networks Lab 17TEL77 2020

getch();
}
}

Output :

Dept. of TCE Page 54


Computer Communication Networks Lab 17TEL77 2020

Program 5

5. Write a Program for Dijkstra’s Algorithm to compute the shortest routing path.

Aim: To simulate Dijkstra‟s Algorithm

Theory:

In order to transfer packets from a source host to the destination host, the network layer must
determine the path or route that packet are to follows. This is the job of the network layer
routing protocol. As the heart of any routing protocol is the routing algorithm that determines
the path for a packet from source router to destination router. Given a set of router, with links
connecting the routers, a routing algorithm finds a good path from source router to destination
router.

Dijkstra‟s method of computing the shortest path is a stating routing algorithm. It involves
building a graph of the subnet, with each node of the graph representing a router and each arc
representing a communication line or a link. To find route between a pair of outer, the algorithm
just finds the shortest path between them on the graph.

Dijkstra‟s algorithm finds the solution for the shortest path problems only when all the edge-
weights are non-negative on a weighted directed graph. In Dijkstra‟s algorithm the metric used
for calculation is distance. Each node is labelled with its distance from the source node along
the best known path. Initially, no paths are known, so all nodes are labelled with infinity. As the
algorithm proceeds and path are found, the labels may change, reflecting better paths. A label
may either be tentative or permanent. Initially all nodes are tentative it is discovered that the
shortest possible path to a node permanent and never be changed.

Dijkstra’s Algorithm

1. Enter cost matrix C [ ] [ ]. C [i] [j] is the cost of going from vertex I to vertex j. if there
is no edge between vertices I and j then C [i] [j] is infinity.
2. Array visited [ ] is
Initialized to
Zero.
For(i=0;i<n;i++)
Visited[ i]=0;
3. If the vertex 0 is the source vertex then visited [0] is marked as 1.
4. Create the distance matrix, by storing the cost of vertices from vertex 0 to n-1 from the
source vertex 0.
For(i=1;i<n;i++)
Distance [i]=cost[0] [i];
Initially, distance of source vertex is taken as 0 i.e. distance[0]=0;
5. i=(1;i<n;i++)
- Recalculate the shortest distance of remaining vertices from the source.

Dept. of TCE Page 55


Computer Communication Networks Lab 17TEL77 2020

- Only, the vertices not marked as 1 in array visited [ ] should be considered for
recalculation of distance. i.e. for each vertex.
6. Sotp the algorithm if, when all the nodes has been marked visited.

Below is an example which further illustrates the Dijkstra‟s algorithm mentioned.


Consider a weighed graph as shown:

Here 0,1,2,3 and 4 which are inside the circle are nodes of the graph, and the numbers
between them are the distance of the graph. Now using Dijkstra‟s algorithm we can find the
shortest path between initial node and the remaining vertices. For this, the cost matrix of the
graph above is,

Cost Matrix:

n 1 2 3 4
0 1 999 3 10
1 0 5 999 999
2 5 0 2 1
3 999 2 0 6
4 999 1 6 0

Program

#include<iostream>
#include<stdio.h>
#include<conio.h>
#include<process.h>
#define infinity 999

Dept. of TCE Page 56


Computer Communication Networks Lab 17TEL77 2020

using namespace std;


void dijkstras(int cost [10][10], int n, int src, int distance[10])
{
int visited[10],min,u,i,j;
for(i=1;i<=n;i++)
{
distance[i]=cost[src][i];

visited[i]=0;
}
visited[src]=1;
for(i=1;i<=n;i++)
{
min=infinity;

for(j=1;j<=n;j++)
if(visited[j]==0 && distance[j]<min)
{
min=distance[j];
u=j;
}

visited[u]=1;
for(j=1;j<=n;j++)

if(visited[j]==0 && (distance[u]+cost[u][j]<distance[j]))


distance[j]=distance[u]+cost[u][j];
}

}
int main()
{
int cost[10][10],distance[10],n,i,j,sum,dist,src;

Dept. of TCE Page 57


Computer Communication Networks Lab 17TEL77 2020

cout<<" \n enter the no of nodes:";


cin>>n;
cout<<"\n enter the cost matrix 0 self loop and 999 no edge connection : \n";
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
cin>>cost[i][j];
cout<<"\n enter the source node";

cin>>src;
cout<<"\enter the destination node";
cin>>dist;
dijkstras(cost,n,src,distance);
cout<<"\n shortest distance from"<<src<<"to"<<dist<<"is"<<distance[dist];
getch();

Output :

Dept. of TCE Page 58


Computer Communication Networks Lab 17TEL77 2020

Program 6

6. Write a Program for RSA (Rivest-Shamir-Adleman) Algorithm for


Encryption and Decryption of data.
Aim: To simulate RSA Algorithm

Theory:

RSA Algorithm is used to encrypt and decrypt data in modern computer systems and
other electronic devices. RSA algorithm is an asymmetric cryptographic algorithm as it creates
2 different keys for the purpose of encryption and decryption. It is public key cryptography as
one of the keys involved is made public.

RSA makes use of prime numbers (arbitrary large numbers) to function. The public key is made
available publicly (means to everyone) and only the person having the private key with them
can decrypt the original message.

Working of RSA Algorithm

RSA involves use of public and private key for its operation. The keys are generated using the
following steps:-

1. Two prime numbers are selected as p and q


2. n = pq which is the modulus of both the keys.
3. Calculate totient = (p-1)(q-1)
4. Choose e such that e > 1 and coprime to totient which means gcd (e, totient) must be equal
to 1, e is the public key
5. Choose d such that it satisfies the equation de = 1 + k (totient), d is the private key not
known to everyone.
6. Cipher text is calculated using the equation c = m^e mod n where m is the message.
7. With the help of c and d we decrypt message using equation m = c^d mod n where d is the
private key.

Note: If we take the two prime numbers very large it enhances security but requires
implementation of Exponentiation by squaring algorithm and square and multiply algorithm for
effective encryption and decryption. For simplicity the program is designed with relatively
small prime numbers.

Program

#include<iostream>
#include<stdio.h>
#include<math.h>

using namespace std;

int gcd(int a, int b)

Dept. of TCE Page 59


Computer Communication Networks Lab 17TEL77 2020

{
while (a!=b)

{
if (a>b)
a=a-b;
else
b=b-a;
}

return (a);

}
int main()

{
double p = 3, q = 5, m;
double n = p*q;
double e = 3; // choose e such that gcd(e,phi)=1
double phi = (p-1)*(q-1);

while (e < phi)


{
if (gcd(e, phi)==1)
break;
else
e++;
}
int k = 5;// choose k such that d*e mod(phi)=1
double d = (1 + (k*phi))/e;// choose d such that d*e mod(phi)=1
cout<<"\n \n Input Message data = ";
cin>> m;
double c= fmod((pow(m,e)),n);
cout<<"\n \n Cipher data ="<<c<<"\n";
m = fmod((pow(c,e)),n);
cout<< "\n \n original data = "<< m<<" \n";
return 0;
}

Output:

Dept. of TCE Page 60


Computer Communication Networks Lab 17TEL77 2020

Program 7

7. Write a Program for Congestion Control using Leaky Bucket


Algorithm
Aim: To simulate Leaky Bucket Algorithm.

Theory:

Network monitors traffic flows continuously to ensure they meet their traffic contract.
The process of monitoring and enforcing the traffic flow is called policing. When a packet
violates the contract, network can discard or tag the packed giving it lower priority. If
congestion occurs, tagged packets are discarded first.

Leaky bucket algorithm is the most commonly used policing mechanism

(i) Bucket has specified leak rate for average contracted rate
(ii) Bucket has specified depth to accommodate variation in arrival rate
(iii) Arriving packet is conforming if it does not result in overflow Leaky bucket
algorithm can be used to police arrival rate of a packet

Program
#include <iostream>

#include <stdio.h>
#include <time.h>
#include <windows.h>

Dept. of TCE Page 61


Computer Communication Networks Lab 17TEL77 2020

#define bucketsize 1000


#define n 5
using namespace std;
void bucketoutput (int *bucket,int op)
{
if(*bucket > 0 && *bucket > op)
{

*bucket= *bucket-op;
//cout<<"\n"<< op <<" - outputed, remaining is " << *bucket;
}
else if( *bucket > 0)
{
cout<< "\n remaining data output = "<< *bucket;

*bucket=0;
}
}
int main()
{
int op,newpack,oldpack=0,wt,i,j,bucket=0;

cout<< "enter output rate: ";


cin>>op;
for(i=1;i<=n;i++)
{
newpack=rand()%500;
//cout<< "\n\n new packet size = " <<newpack;

newpack= oldpack+newpack;
wt=rand()%5;
if(newpack<bucketsize)
bucket=newpack;

Dept. of TCE Page 62


Computer Communication Networks Lab 17TEL77 2020

else
{
cout<< "\n" << newpack << " = the newpacket and old pack is greater than bucketsize reject";
bucket=oldpack;
}
cout<< "\n the data in bucket = "<< bucket;
cout<< "\n the next packet will arrive after = "<<wt<< "sec";

for(j=0;j<wt;j++)
{
bucketoutput(&bucket,op);
Sleep(1);
}
oldpack=bucket;

}
while(bucket>0)
bucketoutput(&bucket,op);
return 0;
}

Output :

Dept. of TCE Page 63

You might also like