You are on page 1of 49

CN LAB (15/17ECL68) Sri Venkateshwara College of Engineering, Bengaluru

SVCE/ECE/MNL./CNL/Ver-01

SRI VENKATESHWARA COLLEGE OF ENGINEERING


VIDYANAGAR, BENGALURU-562157

DEPARTMENT OF
ELECTRONICS & COMMUNICATIONENGINEERING

LAB MANUALFOR
Computer Network Lab
(15/17ECL68)
(VI SEMESTER E&CE)

Prepared by
Mr. RAJENDRA PRASAD P
Mr. RAVI GATTI

2021-2022

Approved By:
Dr. SHIVSHANKAR
HoD, E&CE, SVCE, Bengaluru

Department of Electronics & Communication Engineering Page 1


CN LAB (15/17ECL68) Sri Venkateshwara College of Engineering, Bengaluru

INDEX
Page
Sl. No. Description
No.
1 Course objectives, Course outcomes and Mapping with Programme
3
outcomes
2 Course syllabus 7
PART - A
Simulation experiments using NS2/ NS3/ OPNET/ NCTUNS/ NetSim/
QualNet/ Packet Tracer or any other equivalent tool
Implement a point to pint network with four nodes and duplex links between
1 them. Analyze the network performance by setting the queue size and varying 9
the bandwidth.
Implement a four node point to point network with links n0-n2, n1-n2 and n2-
n3. Apply TCP agent between n0-n3 and UDP between n1-n3. Apply relevant
2 11
applications over TCP and UDP agents changing the parameter and determine
the number of packets sent by TCP/UDP.
Implement Ethernet LAN using n (6-10) nodes. Compare the throughput by
3 13
changing the error rate and data rate.
Implement Ethernet LAN using n nodes and assign multiple traffic to the nodes 15
4
and obtain congestion window for different sources/ destinations.
Implement ESS with transmission nodes in Wireless LAN and obtain the
5
performance parameters. 17
6 Implementation of Link state routing algorithm 19
PART - B : Implement the following in C/C++
Write a program for a HLDC frame to perform the following.
1 i) Bit stuffing 22
ii) Character stuffing.
Write a program for distance vector algorithm to find suitable path for
2 26
transmission.
3 Implement Dijkstra’s algorithm to compute the shortest routing path. 28
For the given data, use CRC-CCITT polynomial to obtain CRC code. Verify the
program for the cases
4 30
a. Without error
b. With error
5 Implementation of Stop and Wait Protocol and Sliding Window Protocol 32
Write a program for congestion control using leaky bucket algorithm.
6 36
Experiments beyond the syllabus
Transmission of ping message
1 38
Using TCP/IP sockets, write a client server program to make client sending the
2 file name and the server to send back the contents of the requested file 42

Implement the TCP/IP sockets, write a client server program using as message
3 queues or FIFOs as IPC channels 48

Department of Electronics & Communication Engineering Page 2


CN LAB (15/17ECL68) Sri Venkateshwara College of Engineering, Bengaluru

COURSE OBJECTIVES
1. To understand the working principle of various communication protocols.
2. To analyze the various routing algorithms.
3. To know the concept of data transfer between nodes.

4. To design wireless and wired network using NS2

5. Understand the concept of Routing algorithm to find shortest path using Distance vector
algorithm

6. Describe the scenario and study the performance of various network protocols through
simulation.

COURSE OUTCOMES
Course Name: COMPUTER NETWORKS LABORATORY (15ECL68)
After Completion of the course the student will be able Level of Blooms
COs
to Taxonomy
C367.1 Choose suitable tools to model a network and understand and
calculate the network parameters of different protocols at L1
various OSI reference levels.

C367.2 Illustrate network performance for the transport layer protocols


such as UDP and TCP L3

C367.3 Simulate the networking concepts and protocols using C/C++


L3
programming.

C367.4 Analyze the different network protocols for network parameters


L4
using C/C++

C367.5 Design and development of a suitable network and simulate


using Network simulator tool. L5

Department of Electronics & Communication Engineering Page 3


CN LAB (15/17ECL68) Sri Venkateshwara College of Engineering, Bengaluru

PROGRAMME OUTCOMES:
1. Engineering Knowledge: Apply knowledge of mathematics, science, engineering
fundamentals and an engineering specialization to the solution of complex engineering
problems.
2. Problem Analysis: Identify, formulate, research literature and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences and engineering sciences

3. Design/ Development of Solutions: Design solutions for complex engineering problems


and design system components or processes that meet specified needs with appropriate
consideration for public health and safety, cultural, societal and environmental
considerations.

4. Conduct investigations of complex problems using research-based knowledge and


research methods including design of experiments, analysis and interpretation of data and
synthesis of information to provide valid conclusions.
5. Modern Tool Usage: Create, select and apply appropriate techniques, resources and modern
engineering and IT tools including prediction and modeling to complex engineering activities
with an under- standing of the limitations.

6. The Engineer and Society: Apply reasoning informed by contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities relevant
to professional engineering practice.
7. Environment and Sustainability: Understand the impact of professional engineering
solutions in societal and environmental contexts and demonstrate knowledge of and need
for sustainable development.
8. Ethics: Apply ethical principles and commit to professional ethics and responsibilities and
norms of engineering practice.
9. Individual and Team Work: Function effectively as an individual, and as a member or
leader in diverse teams and in multi disciplinary settings.
10. Communication: Communicate effectively on complex engineering activities with the
engineering community and with society at large, such as being able to comprehend and
write effective reports and design documentation, make effective presentations and give
and receive clear instructions.
11. Life-long Learning: Recognize the need for and have the preparation and ability to engage
in independent and life- long learning in the broadest context of technological change.
12. Project Management and Finance: Demonstrate knowledge and understanding of
engineering and management principles and apply these to one’s own work, as a member
and leader in a team, to manage projects and in multidisciplinary environments.

Department of Electronics & Communication Engineering Page 4


CN LAB (15/17ECL68) Sri Venkateshwara College of Engineering, Bengaluru

Course outcomes and Program Specific Outcomes

1. Ability to learn and implement the new technologies in Electronics and Communication
domain.
2. Ability to Design and manufacture simple and complex Electronic Circuit boards for various
applications
MAPPING COURSE OUTCOMES WITH PROGRAM OUTCOMES:
Program Outcomes
Course outcomes 1 2 3 4 5 6 7 8 9 10 11 12
C367.1 Choose suitable tools to model a network and 2 2 2 2 2 2 2 2
understand and calculate the network parameters of
different protocols at various OSI reference levels.

C367.2 Design and development of a suitable network and 2 2 2 2 3 2 2 2 2


simulate using Network simulator tool.

C367.3 Simulate the networking concepts and protocols using 3 3 3 3 2 2 2 2


C/C++ programming.

C367.4 Analyze the different network protocols for network 2 3 2 3 1 2 2 2 2


parameters using C/C++

C367.5 Design and of a suitable network and simulate using 2 1 2 2 3 2 2 2 3 3


Network simulator tool.

Note: Enter the correlation level 1, 2 or 3 as defined below:

1: Low 2: Medium 3: STRONG

MAPPING COURSE OUTCOMES WITH PROGRAM SPECIFIC OUTCOMES:

Course outcomes Program Specific Outcomes


PSO1 PSO2
C367.1
2

C367.2
2

C367.3
3

C367.4
2

C367.5
3 2

Enter the correlation level 1, 2 or 3 as defined below:


1: Low 2:Medium 3: STRONG

Department of Electronics & Communication Engineering Page 5


CN LAB (15/17ECL68) Sri Venkateshwara College of Engineering, Bengaluru

Practical Approaches for Bridging the Gap between Syllabus and Industry:

Sl No Topic/CO Industry Lab GAPs


Requirement Experiments

1 Choose suitable tools to model a network Employee should Lack of real time
have the basics examples
and understand and calculate the network knowledge of
parameters of different protocols at Network 1,2,34
various OSI reference levels. simulator

2 Design and development of a suitable Employee should Limited use of network


have experienced simulators
network and simulate using Network in using the 5,6
simulator tool. network
simulators
3 Simulate the networking concepts and Employee should
have strong
protocols using C/C++ programming. Usage of real time data
programming
application in
languages related 1,2,3
programming scenario
to network
concepts

4 Analyze the different network protocols Student should have


Handling with big
for network parameters using C/C++ very good knowledge in
data is needed in 4,5,6 network of the received
industries
data of the network

CURRICULAR GAPS AND CONTENT BEYOND SYLLABUS IMPARTED FOR THE


ATTAINMENT OF THE COs/POs:

SL. Gap Action Date- Resource Percentage Relevance


No Taken Month- Person With of Students to PO’s,
Year Designation PSO’s

1 Lack of real time Additional June, 2021 Course All PO3,PO7,


examples coordinators PO4,
experiments

2 Limited use of Additional June, 2021 Course All PO2, PO3,


network simulators experiments coordinator PO8, PO9

3 Usage of real time Additional July, 2021 Course All PO4, PO8,
data application in experiments coordinators PO12
programming scenario

4 Student should have Additional July, 2021 Course All PO4, PO5,
very good knowledge experiments coordinator PO8
in network of the
received data of the
network

Department of Electronics & Communication Engineering Page 6


CN LAB (15/17ECL68) Sri Venkateshwara College of Engineering, Bengaluru

Course syllabus
PART-A: Simulation experiments using NS2/ NS3/ OPNET/ NCTUNS/ NetSim/
QualNet/ Packet Tracer or any other equivalent tool

1. Implement a point to pint network with four nodes and duplex links between them.
Analyze the network performance by setting the queue size and varying the bandwidth.
2. Implement a four node point to point network with links n0-n2, n1-n2 and n2-n3. Apply
TCP agent between n0-n3 and UDP between n1-n3. Apply relevant applications over TCP
and UDP agents changing the parameter and determine the number of packets sent by
TCP/UDP.
3. Implement Ethernet LAN using n (6-10) nodes. Compare the throughput by changing the
error rate and data rate.
4. Implement Ethernet LAN using n nodes and assign multiple traffic to the nodes and obtain
congestion window for different sources/ destinations.
5. Implement ESS with transmission nodes in Wireless LAN and obtain the performance
parameters.
6. Implementation of Link state routing algorithm

PART-B: Implement the following in C/C++

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


iii) Bit stuffing
iv) Character stuffing.
2. Write a program for distance vector algorithm to find suitable path for transmission.
3. Implement Dijkstra’s algorithm to compute the shortest routing path.
4. For the given data, use CRC-CCITT polynomial to obtain CRC code. Verify the program
for the cases
a. Without error
b. With error
5. Implementation of Stop and Wait Protocol and Sliding Window Protocol
6. Write a program for congestion control using leaky bucket algorithm.

Department of Electronics & Communication Engineering Page 7


CN LAB (15/17ECL68) Sri Venkateshwara College of Engineering, Bengaluru

COMPUTER NETWORKS LAB (15ECL68)


Content beyond syllabus for the Hardware Description Laboratory

LIST OF EXTRA PROGRAMS APART FROM THE CURRICULUM

Sl.No Programs Attainment of


POs

1. Transmission of Ping Message: Simulate the transmission of ping PO3, PO5, PO9,
messages over a network topology consisting of 6 nodes and find the PO11, PO12
number of packets dropped due to congestion. PSO1

2. Using TCP/IP sockets, write a client server program to make PO3, PO5, PO9,
client sending the file name and the server to send back the PO11, PO12

contents of the requested file if present PSO1

3. Implement the TCP/IP sockets, write a client server program PO3, PO5, PO9,
using as message queues or FIFOs as IPC channels PO11, PO12

PSO1

Programme Coordinator

Department of Electronics & Communication Engineering Page 8


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

1. Implement a point to pint network with four nodes and duplex


links between them. Analyze the network performance by setting
the queue size and varying the bandwidth.

set ns [new Simulator]


set f [open lab1.tr w]
$ns trace-all $f

set nf [open lab1.nam w]


$ns namtrace-all $nf

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

set n0 [$ns node]


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

$ns duplex-link $n0 $n1 0.3Mb 10ms DropTail #vary bandwidth 0.3, 0.4, 0.5 0.7
$ns duplex-link $n1 $n2 0.3Mb 20ms DropTail #vary bandwidth 0.3, 0.4, 0.5 0.7
$ns duplex-link $n2 $n3 0.3Mb 20ms DropTail #vary bandwidth 0.3, 0.4, 0.5 0.7

$ns queue-limit $n0 $n1 20


$ns queue-limit $n1 $n2 20
$ns queue-limit $n2 $n3 20

set udp0 [new Agent/UDP]


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

set null0 [new Agent/Null]


$ns attach-agent $n3 $null0

$ns connect $udp0 $null0

$ns at 0.1 "$cbr0 start"


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

Department of Electronics & Communication Engineering Page 9


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

Steps for execution:

 Open gedit editor and type program. Program name should have the extension “ .tcl ”
[root@localhost ~]# gedit lab1.tcl
 Save the program and quit.
 Run the simulation program
[root@localhost~]# ns lab1.tcl
 Here “ns” indicates network simulator. We get the topology shown in the network animator. Now
press the play button in the simulation window and the simulation will begins.
 To calculate the network performance. Execute the following command.
For calculating number of received packets
[root@localhost~]#grep ^r lab1.tr | grep “cbr” | awk „{s+=$6}END{print s}‟
For calculating total time
[root@localhost~]#grep ^r lab1.tr | grep “cbr” | awk „{s+=$2}END{print s}‟

Network performace = (Packet received/ Total Time) (bps)

 Write the value of network performance in observation sheet. Repeat the above step by changing
the bandwidth to [0.3Mb, 0.4Mb, 0.5Mb, 0.7Mb]to the following line of the program.
 $ns duplex-link $n0 $n1 0.7Mb 10ms DropTail #vary bandwidth 0.3, 0.4, 0.5 0.7
 $ns duplex-link $n1 $n2 0.7Mb 20ms DropTail #vary bandwidth 0.3, 0.4, 0.5 0.7
 $ns duplex-link $n2 $n3 0.7Mb 20ms DropTail #vary bandwidth 0.3, 0.4, 0.5 0.7

Sl. Bandwidth Network performance


No.
1. 0.3
2. 0.4
3. 0.5
4. 0.7

 Plot a graph with x- axis with bandwidth and y-axis with network performance of UDP protocol.

Department of Electronics & Communication Engineering Page 10


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

2. Implement a four node point to point network with links n0-n2,


n1-n2 and n2-n3. Apply TCP agent between n0-n3 and UDP
between n1-n3. Apply relevant applications over TCP and
UDP agents changing the parameter and determine the number of
packets sent by TCP/UDP.

set ns [new Simulator]

set f [open lab2.tr w]


$ns trace-all $f

set nf [open lab2.nam w]


$ns namtrace-all $nf

$ns color 1 "Blue"


$ns color 2 "Red"

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

set n0 [$ns node]


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

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


$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns duplex-link $n2 $n3 2.75Mb 20ms DropTail

$ns queue-limit $n2 $n3 50

set tcp0 [new Agent/TCP]


$ns attach-agent $n0 $tcp0
$tcp0 set class_ 1

set ftp0 [new Application/FTP]


$ftp0 attach-agent $tcp0

set sink [new Agent/TCPSink]


$ns attach-agent $n3 $sink
$ns connect $tcp0 $sink

set udp0 [new Agent/UDP]


$ns attach-agent $n1 $udp0

Department of Electronics & Communication Engineering Page 11


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

$udp0 set class_ 2

set cbr0 [new Application/Traffic/CBR]


$cbr0 attach-agent $udp0
$cbr0 set packetSize_ 1000
$cbr0 set interval_ 0.005

set null0 [new Agent/Null]


$ns attach-agent $n3 $null0
$ns connect $udp0 $null0

$ns at 0.1 "$cbr0 start"


$ns at 1.0 "$ftp0 start"
$ns at 4.0 "$ftp0 stop"
$ns at 4.5 "$cbr0 stop"

$ns at 5.0 "finish"


$ns run

Steps for execution:

 Open gedit editor and type program. Program name should have the extension “ .tcl ”
[root@localhost ~]# gedit lab2.tcl
 Save the program and quit.
 Run the simulation program
[root@localhost~]# ns lab2.tcl
 Here “ns” indicates network simulator. We get the topology shown in the network animator. Now
press the play button in the simulation window and the simulation will begins.
 To calculate the number of packets sent by TCP. Execute the following command.

[root@localhost~]#grep ^r lab2.tr | grep “tcp” -c

 To calculate the number of packets sent by UDP. Execute the following command.

[root@localhost~]#grep ^r lab2.tr | grep “cbr” –c

Department of Electronics & Communication Engineering Page 12


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

3. Implement Ethernet LAN using n (6-10) nodes. Compare the


throughput by changing the error rate and data rate.

set ns [new Simulator]


set trf [open lab3.tr w]
$ns trace-all $trf
set naf [open lab3.nam w]
$ns namtrace-all $naf

proc finish { } {
global nf ns tf
exec nam lab3.nam &
close $naf
close $trf
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]

$n1 label "Source"


$n2 label "Error Node"
$n5 label "Destination"

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

$ns duplex-link $n2 $n6 30Mb 100ms DropTail

set udp0 [new Agent/UDP]


$ns attach-agent $n1 $udp0
set cbr0 [ new Application/Traffic/CBR]
$cbr0 attach-agent $udp0
set null5 [new Agent/Null]
$ns attach-agent $n5 $null5
$ns connect $udp0 $null5

$cbr0 set packetSize_ 100


$cbr0 set interval_ 0.001
$udp0 set class_ 1

set err [new ErrorModel]


$ns lossmodel $err $n2 $n6
$err set rate_ 0.7 #vary error rate 0.1, 0.4, 0.5 and 0.7

Department of Electronics & Communication Engineering Page 13


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

$ns at 6.0 "finish"


$ns at 0.1 "$cbr0 start"
$ns run

Steps for execution:

 Open gedit editor and type program. Program name should have the extension “ .tcl ”
[root@localhost ~]# gedit lab3.tcl
 Save the program and quit.
 Run the simulation program
[root@localhost~]# ns lab3.tcl
 Here “ns” indicates network simulator. We get the topology shown in the network animator. Now
press the play button in the simulation window and the simulation will begins.
 To calculate the throughput. Execute the following command.
For calculating number of received packets
[root@localhost~]#grep ^r lab3.tr | grep “2 6” | awk „{s+=$6}END{print s}‟
For calculating total time
[root@localhost~]#grep ^r lab3.tr | grep “2 6” | awk „{s+=$2}END{print s}‟

Throughput = (Packet received/ Total Time) (bps)

 Write the value of throughput in observation sheet. Repeat the above step by changing the error
rate to the following line of the program.

$err set rate_ 0.7 #vary error rate 0.1, 0.4, 0.5 and 0.7

Sl. Error rate Throughput


No.
1. 0.1
2. 0.4
3. 0.5
4. 0.7

 Plot a graph with x- axis with Error rate and y-axis with Throughput.

Department of Electronics & Communication Engineering Page 14


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

4. Implement Ethernet LAN using n nodes and assign multiple traffic


to the nodes and obtain congestion window for different sources/
destinations.

set ns [new Simulator]


set f [open lab4.tr w]
$ns trace-all $f

set nf [open lab4.nam w]


$ns namtrace-all $nf

proc finish {} {
global ns f nf outFile1 outFile2
$ns flush-trace
close $f
close $nf
exec nam lab4.nam &
exec xgraph Congestion1.xg Congestion2.xg -geometry 400x400 &
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]

$n0 label "Src1"


$n4 label "Dst1"
$n1 label "Src2"
$n5 label "Dst2"

$ns make-lan "$n0 $n1 $n2 $n3 $n4 $n5 " 10Mb 30ms LL Queue/DropTail
Mac/802_3

set tcp1 [new Agent/TCP]


$ns attach-agent $n0 $tcp1
set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
set sink1 [new Agent/TCPSink]
$ns attach-agent $n4 $sink1
$ftp1 set maxPkts_ 1000
$ns connect $tcp1 $sink1

set tcp2 [new Agent/TCP/Reno]


$ns attach-agent $n1 $tcp2
set ftp2 [new Application/FTP]
$ftp2 attach-agent $tcp2

Department of Electronics & Communication Engineering Page 15


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

set sink2 [new Agent/TCPSink]


$ns attach-agent $n5 $sink2
$ftp2 set maxPkts_ 1000
$ns connect $tcp2 $sink2

set outFile1 [open Congestion1.xg w]


set outFile2 [open Congestion2.xg w]

proc findWindowSize {tcpSource outFile} {


global ns
set now [$ns now]
set cWindSize [$tcpSource set cwnd_]
puts $outFile "$now $cWindSize"
$ns at [expr $now + 0.1] "findWindowSize $tcpSource $outFile"
}

$ns at 0.0 "findWindowSize $tcp1 $outFile1"


$ns at 0.1 "findWindowSize $tcp2 $outFile2"
$ns at 0.3 "$ftp1 start"
$ns at 0.5 "$ftp2 start"
$ns at 50.0 "$ftp1 stop"
$ns at 50.0 "$ftp2 stop"
$ns at 50.0 "finish"
$ns run

Steps for execution:

 Open gedit editor and type program. Program name should have the extension “ .tcl ”
[root@localhost ~]# gedit lab4.tcl
 Save the program and quit.
 Run the simulation program
[root@localhost~]# ns lab4.tcl
 Here “ns” indicates network simulator. We get the topology shown in the network animator. Now
press the play button in the simulation window and the simulation will begins.
 The xgraph automatically calculates and plot the two graph of Congestion window with TCP1
and TCP2.

Department of Electronics & Communication Engineering Page 16


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

5. Implement ESS with transmission nodes in Wireless LAN and obtain


the performance parameters.

set ns [new Simulator]


set tf [open lab5.tr w]
$ns trace-all $tf
set topo [new Topography]
$topo load_flatgrid 1300 1300
set nf [open lab5.nam w]
$ns namtrace-all-wireless $nf 1300 1300

$ns node-config -adhocRouting DSDV \


-llType LL \
-macType Mac/802_11 \
-ifqType Queue/DropTail/PriQueue\
-channelType Channel/WirelessChannel \
-propType Propagation/TwoRayGround \
-antType Antenna/OmniAntenna \
-ifqLen 50 \
-phyType Phy/WirelessPhy \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON

create-god 3
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
$n0 label "ESS"
$n1 label "mob1"
$n2 label "mob2"
$n0 set X_ 10
$n0 set Y_ 600
$n0 set Z_ 0
$n1 set X_ 80
$n1 set Y_ 600
$n1 set Z_ 0
$n2 set X_ 1200
$n2 set Y_ 600
$n2 set Z_ 0
$ns at 0.1 "$n0 setdest 10 600 15"
$ns at 0.1 "$n1 setdest 80 600 25"
$ns at 0.1 "$n2 setdest 1200 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

Department of Electronics & Communication Engineering Page 17


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

$ns connect $tcp0 $sink1

set tcp1 [new Agent/TCP]


$ns attach-agent $n0 $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 2 "$ftp0 start"


$ns at 15 "$ftp1 start"
$ns at 3 "$n1 setdest 1000 600 250"
$ns at 3 "$n2 setdest 80 600 250"

proc finish { } {
global ns nf tf
$ns flush-trace
exec nam lab5.nam &
close $tf
exit 0
}
$ns at 20 "finish"
$ns run

Steps for execution:

 Open gedit editor and type program. Program name should have the extension “ .tcl ”
[root@localhost ~]# gedit lab5.tcl
 Save the program and quit.
 Run the simulation program
[root@localhost~]# ns lab5.tcl
 Here “ns” indicates network simulator. We get the topology shown in the network animator. Now
press the play button in the simulation window and the simulation will begins.
 To calculate the throughput. Execute the following command.
For calculating number of received packets
[root@localhost~]#grep ^r lab5.tr | grep “AGT” | grep “tcp” | awk „{s+=$8}END{print s}‟
For calculating total time
[root@localhost~]#grep ^r lab5.tr | grep “AGT” | grep “tcp” | awk „{s+=$2}END{print s}‟

Throughput = (Packet received/ Total Time) (bps)

Department of Electronics & Communication Engineering Page 18


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

6. Implementation of Link state routing algorithm.

set ns [new Simulator]

$ns rtproto LS

set nf [open lab6.nam w]


$ns namtrace-all $nf

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

for {set i 0} {$i < 7} {incr i} {


set n($i) [$ns node]
}

for {set i 0} {$i < 7} {incr i} {


$ns duplex-link $n($i) $n([expr ($i+1)%7]) 1Mb 10ms DropTail
}

set udp0 [new Agent/UDP]


$ns attach-agent $n(0) $udp0

set cbr0 [new Application/Traffic/CBR]


$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0

set null0 [new Agent/Null]


$ns attach-agent $n(3) $null0

$ns connect $udp0 $null0

$ns at 0.5 "$cbr0 start"


$ns rtmodel-at 1.0 down $n(1) $n(2)
$ns rtmodel-at 2.0 up $n(1) $n(2)
$ns at 4.5 "$cbr0 stop"
$ns at 5.0 "finish"

$ns run

Department of Electronics & Communication Engineering Page 19


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

Steps for execution:

 Open gedit editor and type program. Program name should have the extension “ .tcl ”
[root@localhost ~]# gedit lab6.tcl
 Save the program and quit.
 Run the simulation program
[root@localhost~]# ns lab6.tcl
 Here “ns” indicates network simulator. We get the topology shown in the network animator. Now
press the play button in the simulation window and the simulation will begins.
 Explain link state routing algorithm using animation. How link state break and rerouting take
place.

Department of Electronics & Communication Engineering Page 20


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

PART-B:

Implement the following in C/C++


1. Write a program for a HLDC frame to perform the following.
i) Bit stuffing
ii) Character stuffing.
2. Write a program for distance vector algorithm to find suitable path
for transmission.
3. Implement Dijkstra’s algorithm to compute the shortest routing
path.
4. For the given data, use CRC-CCITT polynomial to obtain CRC
code. Verify the program for the cases
a. Without error
b. With error
5. Implementation of Stop and Wait Protocol and Sliding Window
Protocol
6. Write a program for congestion control using leaky bucket
algorithm.

Department of Electronics & Communication Engineering Page 21


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

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


i) Bit stuffing

Bit stuffing is a process of inserting an extra bit as 0, once the frame sequence encountered 5
consecutive 1's.
Program
#include<stdio.h>
int main()
{
int a[15];
int i,j,k,n,c=0,pos=0;
printf("\n Enter the number of bits");
scanf("%d",&n);
printf("\n Enter the bits");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
{
if(a[i]==1)
{
c++;
if(c==5)
{
pos=i+1;
c=0;
for(j=n;j>=pos;j--)
{
k=j+1;
a[k]=a[j];
}
a[pos]=0;
n=n+1;
}
}
else
c=0;
}

printf("\n DATA AFTER STUFFING \n");

for(i=0;i<n;i++) {
printf("%d",a[i]);
}

Department of Electronics & Communication Engineering Page 22


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

Execution:

[root@localhost code]# gcc 1a.c


[root@localhost code]# ./a.out

Enter the number of bits


12

Enter the bits


1
0
1
1
1
1
1
1
1
0
1
1

DATA AFTER STUFFING


1011111011011

Department of Electronics & Communication Engineering Page 23


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

ii) Character stuffing.


Character Stuffing is process in which DLESTX and DLEETX are used to denote start and end of
character data with some constraints imposed on repetition of characters.

Program:
#include<stdio.h>
#include<math.h>
#include<stdlib.h>

int main()
{
char c[50],d[50],t[50];
int i,m,j;
printf("enter the number of characters\n");
scanf("%d",&m);
printf("\n enter the characters\n");
for(i=0;i<m+1;i++)
{
scanf("%c",&c[i]);
}
printf("\n original data\n");
for(i=0;i<m+1;i++)
printf("%c",c[i]);
d[0]='d';
d[1]='l';
d[2]='e';
d[3]='s';
d[4]='t';
d[5]='x';
for(i=0,j=6;i<m+1;i++,j++)
{
if((c[i]=='d'&&c[i+1]=='l'&& c[i+2]=='e'))
{
d[j]='d';
j++;
d[j]='l';
j++;
d[j]='e';
j++;
m=m+3;
}
d[j]=c[i];
}
m=m+6;
m++;
d[m]='d';
m++;
d[m]='l';
m++;
Department of Electronics & Communication Engineering Page 24
CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

d[m]='e';
m++;
d[m]='e';
m++;
d[m]='t';
m++;
d[m]='x';
m++;
printf("\n\n transmitted data: \n");
for(i=0;i<m;i++)
{
printf("%c",d[i]);
}
for(i=6,j=0;i <m-6;i++,j++)
{
if(d[i]=='d'&&d[i+1]=='l'&&d[i+2]=='e'&&d[i+3]=='d'&&d[i+4]=='l'&&d[i+
5]=='e')
i=i+3;
t[j]=d[i];
}
printf("\n\nreceived data:");
for(i=0;i<j;i++)
{printf("%c",t[i]);
}
}

Execution:
[root@localhost code]# gcc 1b.c
[root@localhost code]# ./a.out
enter the number of characters
9

enter the characters


abcdabcde

original data

abcdabcde

transmitted data:
dlestx
abcdabcdedleetx

received data:
abcdabcde

Department of Electronics & Communication Engineering Page 25


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

2. Write a program for distance vector algorithm to find suitable path for
transmission.
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.

Program:
#include<stdio.h>

struct node
{
unsigned dist[20];
unsigned from[20];
}rt[10];

int main()
{
int dmat[20][20];
int n,i,j,k,count=0;
printf("\nEnter the number of nodes : ");
scanf("%d",&n);
printf("\nEnter the cost matrix (999 for no link):\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
scanf("%d",&dmat[i][j]);
dmat[i][i]=0;
rt[i].dist[j]=dmat[i][j];
rt[i].from[j]=j;
}
do
{
count=0;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
for(k=0;k<n;k++)
if(rt[i].dist[j]>dmat[i][k]+rt[k].dist[j])
{
rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];
rt[i].from[j]=k;
count++;
}
}while(count!=0);
for(i=0;i<n;i++)
{
printf("\n\nState value for router %d is \n",i+1);
for(j=0;j<n;j++)
{

Department of Electronics & Communication Engineering Page 26


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

printf("\t\nnode %d via %d
Distance%d",j+1,rt[i].from[j]+1,rt[i].dist[j]);
}
}
printf("\n\n");
}

Execution:

[root@localhost code]# gcc 2.c


[root@localhost code]# ./a.out

Enter the number of nodes : 4

Enter the cost matrix (999 for no link):

0 2 999 1
2 0 5 2
999 5 0 6
1 2 6 0

State value for router 1 is

node 1 via 1 Distance0


node 2 via 2 Distance2
node 3 via 2 Distance7
node 4 via 4 Distance1

State value for router 2 is

node 1 via 1 Distance2


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

State value for router 3 is

node 1 via 2 Distance7


node 2 via 2 Distance5
node 3 via 3 Distance0
node 4 via 4 Distance6

State value for router 4 is

node 1 via 1 Distance1


node 2 via 2 Distance2
node 3 via 3 Distance6
node 4 via 4 Distance0

Department of Electronics & Communication Engineering Page 27


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

3. Implement Dijkstra’s algorithm to compute the shortest routing path


Dijkstra algorithm is also called single source shortest path algorithm. The algorithm maintains a
list visited[ ] of vertices, whose shortest distance from the source is calculated.
Program:
#include<stdio.h>
#define INFINITY 9999
#define MAX 10
void dijkstra(int G[MAX][MAX],int n,int startnode);
int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
printf("\nEnter the starting node:");
scanf("%d",&u);
dijkstra(G,n,u);
return 0;
}
void dijkstra(int G[MAX][MAX],int n,int startnode)
{
int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(G[i][j]==0)
cost[i][j]=INFINITY;
else
cost[i][j]=G[i][j];

for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i];
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
{
mindistance=INFINITY;

for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{

Department of Electronics & Communication Engineering Page 28


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

mindistance=distance[i];
nextnode=i;
}

visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}
for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);
j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}
Execution:

[root@localhost code]# gcc 3.c


[root@localhost code]# ./a.out
Enter no. of vertices:5

Enter the adjacency matrix:


0 10 0 30 100
10 0 50 0 0
0 50 0 20 10
30 0 20 0 60
100 0 10 60 0

Enter the starting node:0

Distance of node1=10
Path=1<-0
Distance of node2=50
Path=2<-3<-0
Distance of node3=30
Path=3<-0
Distance of node4=60
Path=4<-2<-3<-0

Department of Electronics & Communication Engineering Page 29


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

4. For the given data, use CRC-CCITT polynomial to obtain CRC code. Verify the
program for the cases
a. Without error
b. With error
Cylic Redundency Check is error checking technique it does error checking via polynomial
division.
Progtam:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define N strlen(g)
char t[128],cs[128],g[]="1000100000010001";
int a,e,c;
void xor(){
for(c=1;c<N;c++)
cs[c]=((cs[c]==g[c])?'0':'1');
}
void crc(){
for(e=0;e<N;e++)
cs[e]=t[e];
do{
if(cs[0]=='1')
xor();
for(c=0;c<N-1;c++)
cs[c]=cs[c+1];
cs[c]=t[e++];
}while(e<=a+N-1);
}
int main(){
printf("\nEnter poly:");
scanf("%s",t);
printf("\nGenerating Polynomial is: %s",g);
a=strlen(t);
for(e=a;e<a+N-1;e++)
t[e]='0';
printf("\nModified t[u] is: %s",t);
crc();
printf("\nChecksum is: %s",cs);
for(e=a;e<a+N-1;e++)
t[e]=cs[e-a];
printf("\nFinal Codeword is: %s",t);
printf("\nTest Error detection 0 (Yes) 1 (No) ? : ");
scanf("%d",&e);

Department of Electronics & Communication Engineering Page 30


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

if(e==0){
printf("Enter postion where error is to be inserted:");
scanf("%d",&e);
t[e]=(t[e]=='0')?'1':'0';
printf("Erroneous Data: %s\n",t);
}
crc();
for(e=0;(e<N-1)&&(cs[e]!='1');e++);
if(e<N-1)
printf("Error Detected");
else printf("No Error Detected");
return 0;
}

Execution:
[root@localhost code]# gcc 4.c
[root@localhost code]# ./a.out

Enter poly : 1011101


Generating Polynomial is : 10001000000100001
Modified t[u] is : 10111010000000000000000
Checksum is : 1000101101011000
Final Codeword is : 10111011000101101011000
Test Error detection 0(yes) 1(no) ? : 0
Enter position where you want to insert error : 3
Errorneous data : 10101011000101101011000
Error detected.

Enter poly : 1011101


Generating Polynomial is : 10001000000100001
Modified t[u] is : 10111010000000000000000
Checksum is : 1000101101011000
Final Codeword is : 10111011000101101011000
Test Error detection 0(yes) 1(no) ? : 1
0No Error Detected.

Department of Electronics & Communication Engineering Page 31


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

5. Implementation of Stop and Wait Protocol and Sliding Window Protocol


5a. Stop and Wait protocol

Program:
#include<stdio.h>
#define w 1
int main()
{
int i,f,frames[50];
printf("\nEnter number of frames to transmit: ");
scanf("%d",&f);
printf("\nEnter %d frames: ",f);
for(i=1;i<=f;i++)
scanf("%d",&frames[i]);
printf("\nWith stop and wait protocol the frames will be sent in the
following manner (assuming no corruption of frames)\n\n");
printf("After sending %d frames at each stage sender waits for
acknowledgement sent by the receiver\n\n",w);
printf("if error occur negative acknowledge is detected same frame is
resend back\n");
for(i=1;i<=f;i++)
{
if((random()%2)==1)
{
if(i%w==0)
{
printf("%d\n",frames[i]);
printf("Acknowledgement of above frames sent is received by
sender\n\n");
}
else
printf("%d ",frames[i]);
}
else
{
sleep(3);
printf("negative acknowledge resend %d frame\n",i);
i=i-1;
sleep(1);
}

}
return 0;
}

Department of Electronics & Communication Engineering Page 32


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

Execution:

[root@localhost code]# gcc 5b.c


[root@localhost code]# ./a.out

Enter number of frames to transmit: 6

Enter 6 frames: 1
4
5
7
8
9

With stop and wait protocol the frames will be sent in the following
manner (assuming no corruption of frames)

After sending 1 frames at each stage sender waits for acknowledgement


sent by the receiver

if error occur negative acknowledge is detected same frame is resend


back
1
Acknowledgement of above frames sent is received by sender

negative acknowledge resend 2 frame


4
Acknowledgement of above frames sent is received by sender

5
Acknowledgement of above frames sent is received by sender

7
Acknowledgement of above frames sent is received by sender

8
Acknowledgement of above frames sent is received by sender

negative acknowledge resend 6 frame


negative acknowledge resend 6 frame
9
Acknowledgement of above frames sent is received by sender

Department of Electronics & Communication Engineering Page 33


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

5b. Sliding window protocol program


Program
#include<stdio.h>

int main()
{
int w,i,f,frames[50];
printf("Enter window size: ");
scanf("%d",&w);
printf("\nEnter number of frames to transmit: ");
scanf("%d",&f);
printf("\nEnter %d frames: ",f);
for(i=1;i<=f;i++)
scanf("%d",&frames[i]);
printf("\nWith sliding window protocol the frames will be sent in the
following manner (assuming no corruption of frames)\n\n");
printf("After sending %d frames at each stage sender waits for
acknowledgement sent by the receiver\n\n",w);
for(i=1;i<=f;i++)
{
if(i%w==0)
{
printf("%d\n",frames[i]);
printf("Acknowledgement of above frames sent is received by
sender\n\n");
}
else
printf("%d ",frames[i]);
}
if(f%w!=0)
printf("\nAcknowledgement of above frames sent is received by
sender\n");
return 0;
}

Execution:

[root@localhost code]# gcc 5b.c


[root@localhost code]# ./a.out
Enter window size: 3

Enter number of frames to transmit: 5

Enter 5 frames: 12 20 87 65 4

With sliding window protocol the frames will be sent in the following
manner (assuming no corruption of frames)

Department of Electronics & Communication Engineering Page 34


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

After sending 3 frames at each stage sender waits for acknowledgement


sent by the receiver

12 20 87
Acknowledgement of above frames sent is received by sender

65 4
Acknowledgement of above frames sent is received by sender

Department of Electronics & Communication Engineering Page 35


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

6. Write a program for congestion control using leaky bucket algorithm


In Leaky bucket, 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.

Program:
#include<stdio.h>
#include<stdlib.h>
int bucket_size;
void bucket_input ( int pkt_sz, int op_rt )
{
if( pkt_sz > bucket_size )
printf(" \n\nBucket overflow\n ");
else
{
sleep(1);
while ( pkt_sz > op_rt )
{
printf(" \n %d bytes outputted ", op_rt );
pkt_sz-= op_rt;
sleep(1);
}
if ( pkt_sz > 0 )
printf(" \nLast %d bytes sent\n", pkt_sz );
printf(" \n Bucket output successful \n" );
}
}
int main()
{
int i, op_rate, packet_size;
printf("\n Enter Bucket Size: " );
scanf( "%d", &bucket_size );
printf(" \n Enter output rate: " );
scanf( "%d", &op_rate );
for( i=1; i<=5; i++ )
{
sleep(1);
packet_size = random()%1000;
printf(" \n Packet number [%d] \t Packet size = %d ", i, packet_size
);
bucket_input( packet_size, op_rate );
}
return 0;
}

Department of Electronics & Communication Engineering Page 36


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

Execution:
[root@localhost code]# gcc 6.c
[root@localhost code]# ./a.out

Enter Bucket Size: 500

Enter output rate: 80

Packet number [1] Packet size = 383


80 bytes outputted
80 bytes outputted
80 bytes outputted
80 bytes outputted
Last 63 bytes sent

Bucket output successful

Packet number [2] Packet size = 886

Bucket overflow

Packet number [3] Packet size = 777

Bucket overflow

Packet number [4] Packet size = 915

Bucket overflow

Packet number [5] Packet size = 793

Bucket overflow

Department of Electronics & Communication Engineering Page 37


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

Additional Programs

Experiment No: 1
TRANSMISSION OF PING MESSAGE

Aim: Simulate the transmission of ping messages over a network topology consisting of 6 nodes and find
the number of packets dropped due to congestion.

set nf [ open lab4.nam w ]


$ns namtrace-all $nf

set tf [ open lab4.tr w ]


$ns trace-all $tf

set n0 [$ns node]


set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
set n5 [$ns node]

$ns duplex-link $n0 $n4 1005Mb 1ms DropTail


$ns duplex-link $n1 $n4 50Mb 1ms DropTail
$ns duplex-link $n2 $n4 2000Mb 1ms DropTail
$ns duplex-link $n3 $n4 200Mb 1ms DropTail
$ns duplex-link $n4 $n5 1Mb 1ms DropTail

set p1 [new Agent/Ping] # letters A and P should be capital


$ns attach-agent $n0 $p1
$p1 set packetSize_ 50000
$p1 set interval_ 0.0001

set p2 [new Agent/Ping] # letters A and P should be capital


$ns attach-agent $n1 $p2

set p3 [new Agent/Ping] # letters A and P should be capital


$ns attach-agent $n2 $p3
$p3 set packetSize_ 30000
$p3 set interval_ 0.00001

set p4 [new Agent/Ping] # letters A and P should be capital


$ns attach-agent $n3 $p4

set p5 [new Agent/Ping] # letters A and P should be capital


$ns attach-agent $n5 $p5

Department of Electronics & Communication Engineering Page 38


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

$ns queue-limit $n0 $n4 5


$ns queue-limit $n2 $n4 3
$ns queue-limit $n4 $n5 2
Agent/Ping instproc recv {from rtt} {
$self instvar node_
puts "node [$node_ id]received answer from $from with round trip time $rtt msec"
}
# please provide space between $node_ and id. No space between $ and from. No space
between and $ and rtt */

$ns connect $p1 $p5


$ns connect $p3 $p4

proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam lab4.nam &
exit 0
}
$ns at 0.1 "$p1 send"
$ns at 0.2 "$p1 send"
$ns at 0.3 "$p1 send"
$ns at 0.4 "$p1 send"
$ns at 0.5 "$p1 send"
$ns at 0.6 "$p1 send"
$ns at 0.7 "$p1 send"
$ns at 0.8 "$p1 send"
$ns at 0.9 "$p1 send"
$ns at 1.0 "$p1 send"
$ns at 1.1 "$p1 send"
$ns at 1.2 "$p1 send"
$ns at 1.3 "$p1 send"
$ns at 1.4 "$p1 send"
$ns at 1.5 "$p1 send"
$ns at 1.6 "$p1 send"
$ns at 1.7 "$p1 send"
$ns at 1.8 "$p1 send"
$ns at 1.9 "$p1 send"
$ns at 2.0 "$p1 send"
$ns at 2.1 "$p1 send"
$ns at 2.2 "$p1 send"
$ns at 2.3 "$p1 send"
$ns at 2.4 "$p1 send"

Department of Electronics & Communication Engineering Page 39


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

$ns at 2.5 "$p1 send"


$ns at 2.6 "$p1 send"
$ns at 2.7 "$p1 send"
$ns at 2.8 "$p1 send"
$ns at 2.9 "$p1 send"
$ns at 0.1 "$p3 send"
$ns at 0.2 "$p3 send"
$ns at 0.3 "$p3 send"
$ns at 0.4 "$p3 send"
$ns at 0.5 "$p3 send"
$ns at 0.6 "$p3 send"
$ns at 0.7 "$p3 send"
$ns at 0.8 "$p3 send"

$ns at 0.9 "$p3 send"


$ns at 1.0 "$p3 send"
$ns at 1.1 "$p3 send"
$ns at 1.2 "$p3 send"
$ns at 1.3 "$p3 send"
$ns at 1.4 "$p3 send"
$ns at 1.5 "$p3 send"
$ns at 1.6 "$p3 send"
$ns at 1.7 "$p3 send"
$ns at 1.8 "$p3 send"
$ns at 1.9 "$p3 send"
$ns at 2.0 "$p3 send"
$ns at 2.1 "$p3 send"
$ns at 2.2 "$p3 send"
$ns at 2.3 "$p3 send"
$ns at 2.4 "$p3 send"
$ns at 2.5 "$p3 send"
$ns at 2.6 "$p3 send"
$ns at 2.7 "$p3 send"
$ns at 2.8 "$p3 send"
$ns at 2.9 "$p3 send"

$ns at 3.0 "finish"


$ns run

Department of Electronics & Communication Engineering Page 40


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

AWK file: (Open a new editor using “vi command” and write awk file and save with “.awk”
extension)

BEGIN{
drop=0;
}
{
if($1= ="d" )
{
drop++;
}
}

END{
printf("Total number of %s packets dropped due to congestion =%d\n",$5,drop);

Department of Electronics & Communication Engineering Page 41


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

Experiment No: 2
Client-server socket programming

Aim: Using TCP/IP Sockets, write a client-server program to make client sending the file name and the
server to send back the contents of the requested file if present.

Sockets are a protocol independent method of creating a connection between processes. Sockets can be
either
 Connection based or connectionless: Is a connection established before communication or does
each packet describe the destination?
 Packet based or streams based: Are there message boundaries or is it one stream?
 Reliable or unreliable: Can messages be lost, duplicated, reordered, or corrupted?

Socket characteristics
Sockets are characterized by their domain, type and transport protocol. Common domains are:
 AF_UNIX: address format is UNIX pathname
 AF_INET: address format is host and port number

Common types are:


 virtual circuit: received in order transmitted and reliably
 datagram: arbitrary order, unreliable

Use of sockets:
 Connection–based sockets communicate client-server: the server waits for a connection from
the client
 Connectionless sockets are peer-to-peer: each process is symmetric.

Department of Electronics & Communication Engineering Page 42


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

socket API
#include<sys/types.h>
#include<sys /socket.h>

Sockaddr :

For the internet family:


struct sockaddr_in {
sa_family_t sin_family; // = AF INET
in_port_t sin_port; // is a port number
struct in_addr sin_addr; // an IP address
}

listen
#include <sys / types.h>
#include <sys / socket.h>
int listen (int sid, int size) ;
Where size it the number of pending connection requests allowed (typically limited by Unix kernels
to 5). Returns the 0 on success, or -1 if failure.

accept
#include <sys / types.h>
#include <sys / socket.h>
int accept(int sid ,struct sockaddr *addrPtr , int *lenPtr )
Returns the socketId and address of client connecting to socket.

if lenPtr or addrPtr equal zero, no address structure is returned.


lenPtr is the maximum size of address structure that can be called, returns the actual value.
Waits for an incoming request, and when received creates a socket for it.

send
#include <sys / types.h>
#include <sys / socket.h>
int send(int sid ,const char *bufferPtr ,int len ,int flag)
Send a message. Returns the number of bytes sent or -1 if failure.
(Must be a bound socket).

flag is either
« 0: default
« MSG OOB: Out-of-band high priority communication
recv
#include <sys / types.h>
#include <sys / socket.h>
int recv ( int sid , char *bufferPtr , int len , int flags)
Receive up to len bytes in bufferPtr. Returns the number of bytes received or -1 on failure.

Department of Electronics & Communication Engineering Page 43


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

flags can be either

Shutdown:
include <sys / types.h>
#include <sys / socket.h>
int shutdown ( int sid , int how)
Disables sending (how=1 or how=2) or receiving (how=0 or how=2). Returns -1 on failure.
Connect
-this is the first of the client calls
#include <sys / types.h>

Source Code:
Client Side:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
#include<string.h>
#define SERV_TCP_PORT 6880
#define SERV_HOST_ADDR "127.0.0.1"
int main()
{
int sockfd;
struct sockaddr_in serv_addr,cli_addr;
char filename[100],buf[1000];
int n;
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr(SERV_HOST_ADDR);
serv_addr.sin_port=htons(SERV_TCP_PORT);
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
printf("Client:cant open stream socket\n");
else
printf("Client:stream socket opened successfully\n");
if(connect(sockfd,(struct sockaddr *)&serv_addr,
sizeof(serv_addr))<0)
printf("Client:cant connect to server\n");
else
printf("Client:connected to server successfully\n");
printf("\n Enter the file name to be displayed :");
scanf("%s",filename);
write(sockfd,filename,strlen(filename));
printf("\n filename transfered to server\n");

Department of Electronics & Communication Engineering Page 44


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

n=read(sockfd,buf,1000);
if(n < 0)
printf("\n error reading from socket");
printf("\n Client : Displaying file content of %s\n",filename);
fputs(buf,stdout);
close(sockfd);
exit(0);

AT CLIENT SIDE
[root@localhost ]# cc tcpc.c
[root@localhost ]# ./a.out
Data Sent
File Content....
Sockets are a mechanism for exchanging data between processes. These processes can either
be on the same machine, or on different machines connected via a network. Once a socket connection
is established, data can be sent in both directions until one of the endpoints closes the connection.
I needed to use sockets for a project I was working on, so I developed and refined a few C++
classes to encapsulate the raw socket API calls. Generally, the application requesting the data is
called the client, and the application servicing the request is called the server. I created two primary
classes, ClientSocket and ServerSocket, that the client and server could use to exchange data.
SERVER SIDE:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
#include<string.h>
#define SERV_TCP_PORT 6880
#define SERV_HOST_ADDR "127.0.0.1"
int main()
{ int sockfd,newsockfd,clilen;
struct sockaddr_in cli_addr,serv_addr;
char filename[25],buf[1000];
int n,m=0;
Department of Electronics & Communication Engineering Page 45
CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

int fd;
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
printf("server:cant open stream socket\n");
else
printf("server:stream socket opened successfully\n");
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_addr.sin_port=htons(SERV_TCP_PORT);
if((bind(sockfd,(struct sockaddr *)
&serv_addr,sizeof(serv_addr)))<0)
printf("server:cant bind local address\n");
else
printf("server:bound to local address\n");
listen(sockfd,5);
printf("\n SERVER : Waiting for client...\n");
for(;;)
{
clilen=sizeof(cli_addr);
newsockfd=accept(sockfd,(struct sockaddr *) &cli_addr,&clilen);
if(newsockfd<0)
printf("server:accept error\n");
else
printf("server:accepted\n");
n=read(newsockfd,filename,25);
filename[n]='\0';
printf("\n SERVER : %s is found and ready to transfer
\n",filename);
fd=open(filename,O_RDONLY);
n=read(fd,buf,1000);
buf[n]='\0';
write(newsockfd,buf,n);
printf("\n transfer success\n");
close(newsockfd);
exit(0)
}
}
Department of Electronics & Communication Engineering Page 46
CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

Output:
[root@localhost ]# cc tcps.c
[root@localhost ]# ./a.out
Received the file name : data.txt
File content sent.

Department of Electronics & Communication Engineering Page 47


CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

Experiment No: 3
Client-Server Communication Using Message Queues or FIFO

Aim: C Program for CLIENT SERVER communication using message Queues or FIFOs as IPC
channels that client sends the file name and the server to send back the contents of the requested file
if present.
Source Code:
#SERVER*/
#include<stdio.h>
#include<fcntl.h>
#include<stdlib.h>
#include<string.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
int main()
{
char filename[100],buf[300],buf1[300];
int num,num2,n,filesize,fl,fd,fd2;
mknod("fifo1",S_IFIFO | 0666,0);
mknod("fifo2",S_IFIFO | 0666,0);
printf("\n Server Online\n");
fd=open("fifo1",O_RDONLY);
printf("Client Online! Waiting for request...\n\n");
while(1)
{
num = read(fd,filename,100);
filename[num]='\0';
fl=open(filename,O_RDONLY);
printf("\n Sever: %s is found!\n transferring the contents\n",filename);
filesize=lseek(fl,0,2);
Department of Electronics & Communication Engineering Page 48
CN LAB(15ECL68) Sri Venkateshwara College of Engineering, Bengaluru

printf("\n File size is %d\n",filesize);


lseek(fl,0,0);
n=read(fl,buf1,filesize);
buf1[n]='\0';
fd2=open("fifo2",O_WRONLY);
write(fd2,buf1,strlen(buf1));
printf("\n SERVER :Transfer completed\n");
exit(1);
}
unlink("fifo1");
unlink("fifo2");
}
Output:
AT SERVER SIDE
[root@localhost ]# cc prg6s.c
[root@localhost ]# ./a.out
SERVER online!
CLIENT online!

Department of Electronics & Communication Engineering Page 49

You might also like