Computer Networks Lab Manual - 14-01-2020
Computer Networks Lab Manual - 14-01-2020
Computer Networks Lab Manual - 14-01-2020
Laboratory Experiments
PART-A: Simulation experiments using NS2/ NS3/ OPNET/ NCTUNS/ NetSim/QualNet or any other
equivalent tool
1. Implement 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.
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.
CO Description
CO1: Choose suitable tools to model a network
CO2: Using the network simulator for learning and practice of networking algorithms
CO3: Illustrate the operations of network protocols and algorithm using C programming
CO4: Simulate the network with different configurations to measure the performance
parameters
CO5: Implement the data link and routing protocol using C Programming
Introduction to Computer Networks Lab
The purpose of this is to acquaint the students with an overview of the Computer Networks from the
perspective how the information is transferred from source to destination and different layers in networks.
This course provides a basis for u. They can understand how the data transferred from source to
destination. They can come to know that how the routing algorithms worked out in network layer
understanding the networking techniques that can take place in computer. A computer network is made of
two distinct subsets of components
Distributed applications are programs running on interconnected computers; a web server, a remote login
server, an e-mail exchanger are examples. This is the visible part of what people call “the Internet”. In this
lecture we will study the simplest aspects of distributed applications. More sophisticated aspects are the
object of lectures called “Distributed Systems” and “Information Systems”. The network infrastructure is
the collection of systems which are required for the interconnection of computers running the distributed
applications. It is the main focus of this lecture. The network infrastructure problem has itself two aspects:
Distance: interconnect remote systems that are too far apart for a direct cable connection Meshing:
interconnect systems together; even in the case of systems close to each other, it is not possible in non-
trivial cases to put cables from all systems to all systems (combinatorial explosion, cable salad
management problem s etc.).
The first step in using NAM is to produce the trace file. The trace file should contain topology information,
for example, nodes, links, as well as packet traces. Usually, the trace file is generated by ns. During an ns
simulation, the user can produce topology configurations, layout information, and packet traces using
tracing events in ns. When the trace file is generated, it is ready to be animated by NAM. Upon start-up
NAM will read the trace file, create topology, pop-up a window, do layout if necessary, and then pause at
the time of the first packet in the trace file. Though its user interface, NAM provides control over many
aspects of animation.
To model a network simulation using NS-2, it is necessary to write a Tcl script describing the topology
(nodes, agents, applications, etc). NS2 provide users with an executable command “ns” which takes one
input argument which is the name of a Tcl simulation scripting file. A simulation trace file is then created
which can be used to plot graphs and/or to create animations. AWK is a scripting language tool used for
manipulating data and generating reports. It searches one or more files to see if they contain lines that
matches with the specified patterns and performs the associated actions.
The Trace file contains 12 columns:Event type, Event time, From Node, To Node, Packet Type, Packet Size,
Flags (indicated by --------), Flow ID, Source address, Destination address, Sequence ID, Packet ID
To visualize the result, use a NAM. You can either start a NAM with the command „nam <nam-file>‟
where „<nam-file>‟ is the name of a NAM trace file that was generated by ns or we can executeit directly
out of the Tcl simulation script for the simulation which we want to visualize.
NS2 supports for simulation of both wired and wireless network and is best suitable for the projects related
to networking as it works on packet transmission scenarios i.e. how packets can be transmitted or received
from source to destination which offers packet level inspection i.e. how it is dropped, percentage of packet
dropped and why it is dropped using various traffic generators which generates traffic using different
parameters.
In general, NS2 provides users with a way of specifying different network protocols and simulating their
corresponding behaviors.Various traffic generators are present for generating traffic at source nodes in
wired network simulation, for example, CBR, VBR, and Exponential etc. NAM stands for Network
AniMator window is a visualization tool used in NS2 to provide outputs on a Window screen which shows
the network scenarios like at what time and at how much rate data packets starts dropping etc.
For detailed study of NS-2, please refer to the ns manual. The ns manual can be downloaded from
http://www.isi.edu/nsnam/ns/doc/ns-doc.pdf
For getting the NS-2 software and installing the package, please refer the ns manual.
Detailed notes on NS2, NAM and Xgraph are given at the end for better understanding. Read these
documents before taking up the NS2 simulation programs in Part-A of Computer Networks Lab.
Note: The NAM topology, Trace file and output plots (graphs) are shown at end of each part-
Aexperiment as a reference.
Part-A
1. Implement a point to point network with four nodes and duplex links between them. Analyse the
network performance by setting the queue size and varying the bandwidth.
ftp0
tcp0
BW=100MB
N0 D=20ms
sink3
Q=20
BW=100MB
D=20ms
Q=20
N2 N3
BW=100MB sink2
N1 D=20ms
Q=20
tcp1
ftp1
N0, N1, N2, N3 Nodes (N0 and N1 are Source Nodes, N2-Intermediate Node,
N3-Destination Node)
sink0, sink1 TCP Agent connected to „N3‟ and it reacts to TCP Packets
Note:
A small wired network topology consisting of four nodes, initially the bandwidth, delay and queue size of
all three duplex links remains same, later the bandwidth is varied to 0.1, 0.01, 0.001 and 500MB and
queue size to 3, 5, 10, 20. FTP is an application layer protocol, which generates packets and transmits it
through transport layer (TCP Protocol). Control and data packets are routed from N0-N2-N3 and N1-N2-
N3. First, the control packets are transmitted between source and destination node to check the
connectivity. The above network topology can also be created using NSG2.1 Tool.
#===================================
# Simulation parameters setup
#===================================
set val(stop) 50.0 ;# time of simulation end
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
Awk Script(lab1.awk)
BEGIN{
a=0
b=0
}
{
if($1=="r"&&$3=="2"&&$4=="3"&&$5=="tcp"&&$6=="1540")
{
a++;
}
if($1=="d"&&$3=="2"&&$4=="3"&&$5=="tcp"&&$6=="1540")
{
b++;
}
}
END{
printf("\n total number of data packets received at Node 3: %d\n", a++);
printf("\n total number of packets dropped between Node 2 and Node 3: %d\n", b++);
}
Step 1: Type the above program in text editor and save it with the filename and extension “.tcl”
ns-Network Simulator
Step 3: Once the simulation is completed, run awk file to observe the output
Simulation Result
Terminal
NAM File
ftp0
tcp0
BW=100MB
N0 D=20ms
Sink3
Q=20
BW=100MB
D=20ms
Q=20
N2 N3
BW=100MB null2
N1 D=20ms
Q=20
udp1
cbr1
null-Agent
This network consists of 4 nodes (N0, N1, N2, N3) as shown in above figure. The duplex links between n0
and n2, n1 and n2, and n2 and n3 have 100 Mbps of bandwidth and 20 ms of delay. Each node uses a
DropTail queue with queue size is 20. A "tcp" agent is attached to n0, and a connection is established to a
tcp "sink" agent attached to n3. The packet size of a "tcp" agent will be of 1540Byte and udp agent will be
1000Byte. A tcp "sink" agent generates and sends ACK packets to the sender (tcp agent) and frees the
received packets. A "udp" agent that is attached to n1 is connected to a "null" agent attached to n3. A "null"
agent just frees the packets received. A "ftp" and a "cbr" traffic generator are attached to "tcp" and "udp"
agents respectively. The "cbr" is set to start at 1.0 sec and stop at 23.0 sec, and "ftp" is set to start at 24.0
sec and stop at 48.0 sec.
#===================================
# Simulation parameters setup
#===================================
set val(stop) 50.0 ;# time of simulation end
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
Awk Script(lab2.awk)
BEGIN{
a=0
b=0
}
{
if($1=="r"&&$4=="2"&&$5=="tcp"&&$6=="1040")
{
a++;
}
if($1=="r"&&$4=="2"&&$5=="cbr"&&$6=="1000")
{
b++;
}
}
END{
printf("\n total number of TCP data packets sent between Node 0 and Node 2: %d\n", a++);
printf("\n total number of UDP data packets sent between Node 1 and Node 2: %d\n", b++);
}
Step 1: Type the above program in text editor and save it with the filename and extension “.tcl”
ns-Network Simulator
Step 3: Once the simulation is completed, run awk file to observe the output
Terminal
NAM File
2. Implement a five node point to point network with links N0- N2, N1- N2, N3-N2 and N2-N3. Apply
TCP agent between N0-N3, N2-N3 and N1-N3. Apply relevant applications over TCP agents
changing the parameter and determine the number of packets sent by TCP.
3. Implement a five node point to point network with links N0- N2, N1- N2, N3-N2 and N2-N3. Apply
UDP agent between N0-N3, N2-N3 and N1-N3. Apply relevant applications over UDP agents
changing the parameter and determine the number of packets sent by UDP.
4. Implement a four node point to point network with links N0- N2, N1- N2 and N2-N3. Apply TCP
agent between N0-N3 and N1-N3. Apply relevant applications over TCP agents changing the
parameter and determine the number of packets sent by TCP.
5. Implement a four node point to point network with links N0- N2, N1- N2 and N2-N3. Apply UDP
agent between N0-N3 and N1-N3. Apply relevant applications over UDP agents changing the
parameter and determine the number of packets sent by UDP.
3. Implement Ethernet LAN using N (6-10) nodes. Compare the throughput by changing the error
rate and data rate.
cbr
udp
N0 N1 N2 N3
LAN1
LAN2
N5 N6 N7 N4
null
This network consists of 8 nodes (N0, N1, N2, N3, N4, N5, N6, N7) as shown in above figure. Four nodes
(N0, N1, N2, N3) are attached to LAN1 and other four nodes are attached to LAN2, which is have 100
Mbps of bandwidth and 300 ms of delay and each node uses a DropTail queue. The agent "udp" is attached
to N1, and a connection is established to a "null" agent attached to N7 and the packet size of udp agent will
be 1000Byte. The packets are transmitted from node N1 to LAN1-N3-N4-LAN2-N7 and an error model is
introduced between the path of LAN1 and LAN2. The function of error model is to drop the packets that
are transmitted to it and higher the error rate more the packets are dropped. Throughput is the performance
parameter of the network which depends upon packet received, packet size and simulation time.
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 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
# 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
proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam lab3.nam &
exit 0
}
BEGIN{
a=0
}
{
if($1=="r"&&$4=="7"&&$5=="cbr"&&$6=="1000")
{
a++;
}
}
END{
printf("\n total number of data packets at Node 7: %d\n", a++);
}
ns-Network Simulator
Step 3: Once the simulation is completed, run awk file to observe the output
Simulation Result
Serial Received at Throughput
Error Rate Data Rate
No. Node 7 (kbps)
Note:
Terminal
NAM File
Trace File
Assignment Problems
1. Implement Ethernet LAN using N (6-10) nodes. Compare the packet loss by changing the
error rate and data rate.
2. Implement Ethernet LAN using N (6-10) nodes. Compare the packet delivery ratio by
changing the error rate and data rate.
3. Implement Ethernet LAN using N (6-10) nodes. Compare the packet sent by changing the
error rate and data rate.
4. Implement Ethernet LAN using N (6-10) nodes. Compare the packet received by changing the
error rate and data rate.
5. Implement Ethernet LAN using N (6-10) nodes. Compare the throughput by changing the
bandwidth.
4. Implement Ethernet LAN using N nodes and assign multiple traffic to the nodes
and obtain congestion window for different sources/ destinations
ftp0
sink1 N1 N0 tcp0
LAN1
tcp2 N2 N3 sink3
ftp2
This network consists of 4 nodes (N0, N1, N2, N3) connected to single LAN1 and, node N0 and N2 are
connected to traffic generator (ftp) act as source. Node N1 and N3 are connected to TCP agent sink, works
as destination. Source node N2 and N0 sends the packets to N1 and N3 through common channel LAN1.
After the execution of this program, we will get two output files such as file1.tr and file2.tr; these are
attached to node N0 and N2. File1.tr and file2.tr consists of time period, congestion window size, source
and destination address and port number. Congestion window size keep on increasing continuously till
successful transmission and it resets window size to one, when source node start getting negative
acknowledge packets.
ns-Network Simulator
Step 3: Once the simulation is completed, run awk file to observe the output
Network Animator
20 TCP
10
0
1 2 3 4
Simulation Time
Assignment Problem
1. Implement Ethernet LAN using N nodes and assign three traffic to the nodes and obtain
congestion window for different sources/ destinations
2. Implement two Ethernet LAN using 4 nodes and assign multiple traffic to the nodes and
obtain congestion window for different sources/ destinations
3. Implement Ethernet LAN using 6 nodes and assign multiple traffic to the nodes and obtain
congestion window for different sources/ destinations
4. Implement ESS with transmission nodes in Wireless LAN and obtain then
Performance Parameters.
N7
N6
ftp0 ftp4
N0 N3
tcp0 tcp11
N1 N2 N4 N5
sink10
sink9
The above network consists of 8 nodes, among these nodes N1 and N4 acts as source and, N2 and N5 as
destination. Node N0 and N3 performs as access point 1 and 2, whereas N6 and N7 behaves as router and
server/gateway. This network has 2 BSS group (Basic Service Set) i.e N0, N1, N2 and N3, N4, N5. Group
of more than one BSS is called as ESS (Extended Service Set).
Node N1 sends tcp packets to N5 through N1-N0-N6-N3-N5 similarly N4 sends tcp packets to N2 through
the path N4-N3-N6-N0-N2.
#===================================
# Simulation parameters setup
#===================================
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) 8 ;# number of mobilenodes
set val(rp) AODV ;# routing protocol
set val(x) 2483 ;# X dimension of topography
set val(y) 2506 ;# Y dimension of topography
set val(stop) 6.0 ;# time of simulation end
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
#===================================
# Mobile node parameter setup
#===================================
$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 \
-agentTrace ON \
-routerTrace ON \
-macTrace ON \
-movementTrace ON
#===================================
# Nodes Definition
#===================================
#Create 8 nodes
set n0 [$ns node]
$n0 set X_ 1752
$n0 set Y_ 1142
$n0 set Z_ 0.0
$ns initial_node_pos $n0 20
set n1 [$ns node]
$n1 set X_ 1590
$n1 set Y_ 962
$n1 set Z_ 0.0
$ns initial_node_pos $n1 20
set n2 [$ns node]
$n2 set X_ 1862
$n2 set Y_ 950
$n2 set Z_ 0.0
$ns initial_node_pos $n2 20
set n3 [$ns node]
$n3 set X_ 2202
$n3 set Y_ 1171
$n3 set Z_ 0.0
$ns initial_node_pos $n3 20
set n4 [$ns node]
$n4 set X_ 2135
$n4 set Y_ 982
$n4 set Z_ 0.0
$ns initial_node_pos $n4 20
set n5 [$ns node]
$n5 set X_ 2383
$n5 set Y_ 1029
$n5 set Z_ 0.0
$ns initial_node_pos $n5 20
set n6 [$ns node]
$n6 set X_ 1975
$n6 set Y_ 1202
$n6 set Z_ 0.0
$ns initial_node_pos $n6 20
set n7 [$ns node]
$n7 set X_ 1971
$n7 set Y_ 1406
$n7 set Z_ 0.0
$ns initial_node_pos $n7 20
ns-Network Simulator
Step 3: Once the simulation is completed, run awk file to observe the output
udp0
cbr0
N0 N1
N2 N3
null1
N4
The above network consists of 5 nodes in which node N0 and N4 acts as source and destination and other
nodes behaves as intermediate nodes. There are five paths for sending cbr packets from N0 to N4 such as,
N0-NI-N3-N4
N0-N2-N3-N4
N0-N3-N4
N0-N1-N2-N3-N4
N0-N2-N1-N3-N4
Among these entire paths, link state algorithm will find out the shortest path based on cost assigned to each
link.
#===================================
# Simulation parameters setup
#===================================
set val(stop) 10.0 ;# time of simulation end
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
#===================================
# Agents Definition
#===================================
#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
#===================================
# Applications Definition
#===================================
#Setup a CBR Application over UDP connection
set cbr0 [new Application/Traffic/CBR]
$cbr0 attach-agent $udp0
$cbr0 set packetSize_ 1500
$cbr0 set rate_ 1.0Mb
$cbr0 set random_ null
$ns at 1.0 "$cbr0 start"
$ns at 5.0 "$cbr0 stop"
$ns rtproto LS
#===================================
# Termination
#===================================
#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
ns-Network Simulator
Step 3: Once the simulation is completed, run awk file to observe the output
Simulation Results:
s
Part-B
Bit Stuffing
Simply, Bit stuffing is the process of adding one extra 0 whenever five consecutive 1s follow a 0 in the
data. In a bit-oriented protocol, the data to send is a series of bits. In order to distinguish frames, most
protocols use a bit pattern of 8-bit length (01111110) as flag at the beginning and end of each frame. Here
also cause the problem of appearance of flag in the data part to deal with this an extra bit added. This
method is called bitstuffing. In bit stuffing, if a 0 and five successive 1 bits are encountered, an extra 0 is
added. The receiver node removes the extra-added zero.
CODING:
Program: bitstuf.c
// Program for Bit stuffing
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char a[100],b[100];
int i,j,k,count,n,flag;
strcpy(a,""); strcpy(b,"");
for(;;){
flag=0;
printf("Enter input frame (0's & 1's only):");
scanf("%s",a);
n = strlen(a);
for(i=0; i<n; i++){
if ((a[i]=='0') || (a[i]=='1' )){
continue;
}
else{
flag=1; break;
}
}
if(flag){
printf ("Invalid Input frame\n:");
exit (0);
}
else{
printf ("Valid Input frame\n:");
printf ("Frame length = %d\n", n); break;
}
}
i=0; j=0; flag=0;
while(i<n)
{
if (a[i]=='1')
{
b[j] = a[i]; count=1;
for(k=i+1; a[k]=='1' && k<n && count<5; k++)
{
j++;
b[j]=a[k];
count++;
if(count==5)
{
j++;
b[j]='0'; count=0;
}
i=k;
}
if(k<n){
if(a[k]=='0'){
j++;
b[j] = a[k];
}
i=k;
}
else{ flag=1; break; }
}
else{
b[j] = a[i];
i++;
j++;
}
}
j++; b[i] = '\0';
Theory:
The character-oriented protocols are popular only with text data. Use reserved characters to indicate the
start and end of a frame. For instance, use the two-character sequence DLE STX (Data-Link Escape Start
of TeXt) to signal the beginning of a frame, and the sequence DLEETX (End of TeXt) to flag the frame‟s
end.
The framing method gets around the problem of resynchronization after an error by having each frame
starts with the ASCII character sequence DLESTX (Data Link Escape start of Text) and the sequence
DLEETX (Data Link Escape End of Text). If the destination loses the track of frame boundaries all it has
to do is look for DLESTX and DLEETX characters to figure out. The data link layer on the receiving end
removes DLE before the data are given to the network layer. This technique is called byte stuffing or
character stuffing.
Algorithm
1. Read the character stream from the user.
2. Measure the length of the entered sequence.
3. Read the source delimiter characters from the
4. Check for character sequence with source and destination delimiters of the given pattern.
5. If characters are in the sequence equal to delimiter characters, attach the same characters
immediately after those characters.
6. Go to step-5 to repeat the process for the remaining.
7. Display the result.
program: bytestuf.c
// Program for Character stuffing
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char c[80],d[80],ed[10],sd[10];
inti,j,m;
strcpy(c,"");
strcpy(sd,"dlestx");
strcpy(ed,"dleetx");
Output:
Enter the characters to be stuffed: javed
Result: Thus the program for bit stuffing and character stuffing is executed
Experiment No: 2 Distance Vector Algorithm
Aim: C program for Distance vector algorithm to find suitable path for transmission.
Basically obtain Routing table art each node using distance vector routing algorithm for
given subnet.
In distance vector routing, each router maintains a routing table indexed by, and containing one entry for,
each router in the subnet. This entry contains two parts: the preferred outgoing line to use for that
destination and a distance to that destination. The router is assumed to know the “distance” to each of its
neighbour.
Because each router depends on its neighbors for information, which the neighbors in turn may have
learned from their neighbors, and so on, distance vector routing is sometimes facetiously referred to as
"routing by rumor." The common Characteristics are
Periodic Updates
Periodic updates means that at the end of a certain time period, updates will be transmitted.
Neighbors
The starting assumption for distance-vector routing is that each node knows the cost of the link to each of
its directly connected neighborsIn the context of routers, neighbors always mean routers sharing a common
data link. Distance vector routing information may be, Network ID, Cost and NextHop. These three
essentials need to form a Distance vector‟s routing table.
Design
Algorithm
1. Start the program.
2. Read the number of nodes in the given network.
3. Read the distance matrix from the user. It represents cost distance of each node which connected
directly.
4. By convention, the distance of the node to itself is assigned to zero and when a node is unreachable
the distance is accepted as 999.
5. Store above values in a suitable variable and display the complete routing table.
6. Enter the source node and destination node to find the shortest.
7. Calculate the minimum distance by iteration. If the distance cost between the two nodes is smaller
than the available cost, replace the existence distance with calculated distance.
8. Display the shortest path calculated and its cost between source node and destination node.
9. Go to step-7, to find other short route between other nodes or else goto next step.
10. End the program.
Program: dist_vector.c
// Program for Distance Vector Routing algorithm
#include <stdio.h>
#include <stdlib.h>
#define nul 1000
#define nodes 10
int no=5;
struct node
{
int a[nodes][3];
}
router[nodes];
void init(int r)
{
int i;
no = 5;
for(i=1; i<=no; i++)
{
init(i);
inp(i);
}
printf("\n The configuration of the nodes after initialization is as follows:");
for(i=1; i<=no; i++)
display(i);
while(1)
{
printf("\n\n Enter 1 to continue, 0 to quit:");
scanf("%d",&choice);
if(choice!=1)
break;
printf("\n Enter the nodes between which shortest path is to be found:");
scanf("%d%d",&x,&y);
printf("\n The shortest path is:");
printf("%d--->",x);
find(x,y);
printf("%d",y);
printf("\n The length of the shortest path is %d",router[x].a[y][2]);
}
return 0;
}
Output:
Compile and run
Aim: Implement Dijkstra‟s algorithm to compute the shortest path through a given
graph using C program
Design
Algorithm:
1. Assign to every node a tentative distance value: set it to zero for our initial node and infinity for all other
nodes.
2. Set the initial node as current. Mark all other nodes unvisited. Create a set of all the unvisited nodes
called the unvisited set.
3. For the current node, consider all of its neighbors and calculate their tentative distances. Compare the
newly calculated tentative distance to the current assigned value and assign the smaller one. For example, if
the current node A is marked with a distance of 6, and the edge connecting it with a neighbour B has length
2, then the distance to B (through A) will be 6 +2 = 8. If B was previously marked with a distance greater
than 8 then change it to 8. Otherwise, keep the current value.
4. When we are done considering all of the neighbours of the current node, mark the current node as visited
and remove it from the unvisited set. A visited node will never be checked again.
5. If the destination node has been marked visited (when planning a route between two specific nodes) or if
the smallest tentative distance among the nodes in the unvisited set is infinity (when planning a complete
traversal; occurs when there is no connection between the initial node and remaining unvisited nodes), then
stop. The algorithm has finished.
6. Otherwise, select the unvisited node that is marked with the smallest tentative distance, set it as the new
“current node”, and go back to step 3.
program: dijkstra.c
//Program for Dijkstra‟s Algorithm for shortest path
#include <stdio.h>
#include <stdlib.h>
j=i;
do{
j=pred[j];
printf("%d", j);
}while(j!=startnode);
}
}
Output:
Result: Thus the program implement Dijkstra„s algorithm to compute the Shortest path through a
graph is executed
Experiment No: 4 Error Detecting Code Using CRC-CCITT (16-bit)
Theory: CRC (Cyclic Redundancy Check)
The cyclic redundancy check, or CRC, is a technique for detecting errors in digital data, but not for making
corrections when errors are detected. It is used primarily in data transmission.
This Cyclic Redundancy Check is the most powerful and easy to implement technique. CRC is based on
binary division. In CRC, a sequence of redundant bits, called cyclic redundancy check bits, are appended to
the end of data unit so that the resulting data unit becomes exactly divisible by a second, predetermined
binary number. At the destination, the incoming data unit is divided by the same number. If at this step
there is no remainder, the data unit is assumed to be correct and is therefore accepted. A remainder
indicates that the data unit has been damaged in transit and therefore must be rejected.
CRC is a very effective error detection technique. If the divisor is chosen according to the previously
mentioned rules, its performance can be summarized as follows:
Algorithm
program: crc.c
// Program for CRC Algorithm
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
if (mode) {
for ( i = 0; i < strlen(poly); i++)
strcat(op, "0");
}
/* Perform XOR on the msg with the selected polynomial */
for (j = 0; j < strlen(ip); j++) {
if (op[j] == '1') {
for (k = 0; k < strlen(poly); k++) {
if ((op[j + k] == '0') && (poly[k]=='0') || (op[j+k] == '1') && (poly[k] =='1'))
op[j + k] = '0';
else
op[j +k] = '1';
}
}
}
int main()
{
inti,n,flag;
charip[50], op[50], recv[50];
char poly[] = "10001000000100001";
if(flag){
printf ("Invalid input message\n:");
exit (0);
}
crc(ip, op, poly, 1);
printf("The transmitted message is: %s%s\n",ip,op/*+strlen(ip)*/);
printf("Enter the received message in binary\n");
scanf("%s", &recv);
if(!crc(recv, op, poly, 0))
printf("No error in data\n");
else
printf("Error in data transmission has occurred\n");
return 0;
}
Output:
Compile and run
[root@localhost ]
Aim: C Program for stop and wait protocol and Sliding Window Protocol
Stop and wait is the fundamental technique to provide reliable transfer under unreliable packet delivery
system. After transmitting one packet, the sender waits for an acknowledgment (ACK) from the receiver
before transmitting the next one. In this way, the sender can recognize that the previous packet is
transmitted successfully and we could say "stop-n-wait" guarantees reliable transfer between nodes. To
support this feature, the sender keeps a record of each packet it sends. Also, to avoid confusion caused by
delayed or duplicated ACKs, "stop-n-wait" send each packet with unique sequence numbers and receive
that numbers in each ACK. If the sender doesn't receive ACK for previous sent packet after a certain period
of time, the sender times out and retransmit that packet again. There are two cases when the sender doesn't
receive ACK; one is when the ACK is lost and the other is when the frame itself is not transmitted. To
support this feature, the sender keeps timer per each packet.
The main disadvantage of this method is that it is inefficient. It makes the transmission process slow. In
this method single frame travels from source to destination and single acknowledgment travels from
destination to source. As a result each frame sent and received uses the entire time needed to traverse the
link. Moreover, if two devices are distance apart, a lot of time is wasted waiting for ACKs that leads to
increase in total transmission time.
ALGORITHM
Step 1: Start the program
Step 2: Generate random that gives the total number of frames to be transmitted.
Step 3: Transmit the first frame
Step 4: Receive the acknowledgement for that frame
Step 5: Transmit the next frame
Step 6: Find the remaining frames to be sent
Step 7: If an acknowledgement is not received for a particular frame retransmit that frame alone again.
Step 8: Repeat the steps 5 to 7 till the number of remaining frames to be sent becomes zero.
Step 9: Stop the program.
program: stopnwait.c
// Program for Stop and waitprotocol
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int i,j,noframes;
int x,x1,x2;
No of frames is 6
Sending frame 1
Acknowledgement for frame 1
Sending frame 2
Acknowledgement for frame 2
Sending frame 3
Acknowledgement for frame 3
Sending frame 4
Acknowledgement for frame 4
Sending frame 5
Waiting for 1 second
Sending frame 5
Acknowledgement for frame 5
Sending frame 6
Waiting for 1 second
Sending frame 6
Acknowledgement for frame 6
End of stop and wait protocol
[root@localhost ]#
Theory:
In computer networks sliding window protocol is a method to transmit data on a network. Sliding
window protocol is applied on the Data Link Layer of OSI model. At data link layer data is in the form
of frames. In Networking, Window simply means a buffer which has data frames that needs to be
transmitted.
Both sender and receiver agree on some window size. If window size=w then after sending w frames
sender waits for the acknowledgement (ack) of the first frame.
As soon as sender receives the acknowledgement of a frame it is replaced by the next frames to be
transmitted by the sender. If receiver sends a collective or cumulative acknowledgement to sender then
it understands that more than one frames are properly received, for eg:- if ack of frame 3 is received it
understands that frame 1 and frame 2 are received properly.
In sliding window protocol the receiver has to have some memory to compensate any loss in
transmission or if the frames are received unordered.
W = Window Size
tx = Transmission time
tp = Propagation delay
Sliding window works in full duplex mode
It is of two types:-
1. Selective Repeat: Sender transmits only that frame which is erroneous or is lost.
2. Go back n: Sender transmits all frames present in the window that occurs after the error bit
including error bit also.
Algorithm:
1. Start the program
2. Read the window size
3. Read number of frames to transmit
4. Read randomly selected frames to transmit
5. Transfer the packet until it reaches the maximum defined size.
6. Reduce the window size and repeat the above two steps until packets in.
7. Stop the program
program: slidingwindow.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int w,i,f,frames[50];
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;
}
Output
Output:
-------------------------------------------------------------------------------------------------------
Case-1: For Window Size < No. of Frames
Each host is connected to the network by an interface containing a leaky bucket that is a finite internal
queue where all the incoming packets are stored in case there is space in the queue, otherwise the
packets are discarded. This arrangement can be built into the hardware interface or simulated by the
host operating system. The host is allowed to put one packet per clock into the network. This
mechanism turns an uneven flow of packet from the user process inside the host into an even flow of
packets onto the network, smoothing out bursts and greatly reducing the chances of congestion.
In the following figure we can notice the main rationale of leaky bucket algorithm, for both the two
approaches (e.g. leaky bucket with water (a) and with packets (b)).
program: leakybucket.c
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
int min(int x, int y)
{
if(x<y)
return x;
else
return y;
}
int main()
{
int drop=0, count=0, inp[25];
int mini, nsec, cap, i, process;
printf("\t\t%d",count);
printf("\t\t%d\n",drop);
drop=0;
}
for(;count!=0;i++)
{
if(count>cap)
{
drop=count-cap;
count=cap;
}
printf("%d",i+1);
printf("\t0");
mini=min(count, process);
printf("\t\t%d", mini);
count=count-mini;
printf("\t\t%d", count);
printf("\t\t%d\n", drop);
}
}
Output:
Compile and run
Second|PacketRecieved|PacketSent|PacketLeft|Packet Dropped|
---------------------------------------------------------------------------------
1 5 2 3 0
2 4 2 3 2
3 3 2 3 1
4 0 2 1 0
5 0 1 0 0
[root@localhost ]#
Result: Implemented program for Leaky bucket algorithm and evaluated.
NS2 consists of two key languages: C++ and OTcl (Object-Oriented Tool Command Language). C++
language defines theinternal/ backend mechanism of the simulation by assembling and configuring the
objects as well as scheduling the discrete/frontend events. Both C++ and OTcl are linked with each
other using TclCL. The combination of both languages interpretthe scripts line by line the code written
in gedit in Linux, ms-word or in the notepad in Windows etc. and saves the interpreted file with .tcl
extension. NS2provides a large number of built-in C++ classes which can be used to set-up a
simulation via a Tcl simulation script. One candevelop their own C++ classes and can use a OTcl
configuration interface to put together the objects originated from these class.
After simulation, NS2 provides output as a Text-Based simulation results which can be interpreted
graphically and interactivelyusing tools such as NAM (Network AniMator) and Xgraph. To analyze a
particular behavior of the network, user can transportthat Text-Based data into a more conceivable
presentation.
Introduction to NS-2:
Widely known as NS2, is simply an event driven simulation tool.
Useful in studying the dynamic nature of communication networks.
Simulation of wired as well as wireless network functions and protocols (e.g., routing
algorithms, TCP, UDP) can be done using NS2.
In general, NS2 provides users with a way of specifying such network protocols and simulating
their corresponding behaviors.
Tcl scripting
• Tcl is a general purpose scripting language. [Interpreter]
• Tcl runs on most of the platforms such as UNIX, Windows, and Mac.
Basics of TCL
Syntax: command arg1 arg2 arg3
Hello World!
puts stdout{Hello, World!}
Hello, World!
Variables Command Substitution
set a 5 set len [string length foobar]
set b $a set len [expr [string length foobar] + 9]
Simple Arithmetic
expr 7.2 / 4
Procedures
procDiag {a b} {
set c [expr sqrt($a * $a + $b * $b)]
return $c }
puts “Diagonal of a 3, 4 right triangle is [Diag 3 4]”
Output: Diagonal of a 3, 4 right triangle is 5.0
Loops
while{$i < $n} { for {set i 0} {$i < $n} {incr i} {
... ...
} }
Wired TCL Script Components
Create the event scheduler
Open new files & turn on the tracing
Create the nodes
Setup the links
Configure the traffic type (e.g., TCP, UDP, etc.)
Set the time of traffic generation (e.g., CBR, FTP)
Terminate the simulation
NS Simulator Preliminaries
1. Initialization and termination aspects of the ns simulator.
2. Definition of network nodes, links, queues and topology.
3. Definition of agents and of applications.
4. The nam visualization tool.
5. Tracing and random variables.
Which is thus the first line in the tcl script? This line declares a new variable as using the set command,
you can call this variable as you wish, In general people declares it as ns becauseit is an instance of the
Simulator class, so an object the code[new Simulator] is indeed an instance of the class Simulator using
the reserved word new.
In order to have output files with data on the simulation (trace files) or files used for visualization (nam
files), we need to create the files using “open” command:
#Open the Trace file set tracefile1 [open out.tr w]
The above creates a data trace file called “out.tr” and a nam visualization trace file called
“out.nam”.Within the tcl script,these files are not called explicitly by their names,but instead by
pointers that are declared above and called “tracefile1” and “namfile” respectively. Remark that they
begin with a #symbol.The second line open the file “out.tr” to be used for writing,declared with the
letter “w”.The third line uses a simulator method called trace-all that have as parameter the name of the
file where the traces will go.
The last line tells the simulator to record all simulation traces in NAM input format.It also gives the file
name that the trace will be written to later by the command $ns flush-trace.In our case,this will be the
file pointed at by the pointer “$namfile”, i.e. the file “out.tr”.
Proc finish {} {
$ns flush-trace
Close $tracefile1
Close $namfile
Exit 0
The word proc declares a procedure in this case called finish and without arguments. The word global
is used to tell that we are using variables declared outside the procedure. The simulator method “flush-
trace” will dump the traces on the respective files. The tcl command “close” closes the trace files
defined before and exec executes the nam program for visualization. The command exit will ends the
application and return the number 0 as status to the system. Zero is the default for a clean exit. Other
values can be used to say that is a exit because something fails.
At the end of ns program we should call the procedure “finish” and specify at what time the termination
should occur. For example,
$ns at 125.0 “finish”
will be used to call “finish” at time 125sec.Indeed,the at method of the simulator allows us to schedule
events explicitly.
$ns run
The node is created which is printed by the variable n0. When we shall refer to that node in the script
we shall thus write $n0.
Once we define several nodes, we can define the links that connect them. An example of a definition of
a link is:
$ns duplex-link $n0 $n2 10Mb 10ms DropTail
Which means that $n0 and $n2 are connected using a bi-directional link that has 10ms of propagation
delay and a capacity of 10Mb per sec for each direction.
In ns, an output queue of a node is implemented as a part of each link whose input is that node. We
should also define the buffer capacity of the queue related to each link. An example would be:
There are number variants of the TCP protocol, such as Tahoe, Reno, New Reno, Vegas. The type of
agent appears in the first line:
settcp[new Agent/TCP]
The command $ns attach-agent $n0 $tcp defines the source node of the tcp connection.
The command set sink [new Agent /TCPSink]
defines the behavior of the destination node of TCP and assigns to it a pointer called sink.
The command $ns attach-agent $n4 $sink defines the destination node. The command $ns connect
$tcp $sink finally makes the TCP connection between the source and destination nodes.
TCP has many parameters with initial fixed defaults values that can be changed if mentioned explicitly.
For example, the default TCP packet size has a size of 1000bytes.This can be changed to another value,
say 552bytes, using the command $tcp set packetSize_ 552.
When we have several flows, we may wish to distinguish them so that we can identify them with
different colors in the visualization part. This is done by the command $tcp set fid_ 1 that assigns to
the TCP connection a flow identification of “1”.We shall later give the flow identification of “2” to the
UDP connection.
Scheduling Events
NS is a discrete event based simulation. The tcp script defines when event should occur. The
initializing command set ns [new Simulator] creates an event scheduler, and events are then scheduled
using the format:
$ns at <time><event>
The scheduler is started when running ns that is through the command $ns run.
The beginning and end of the FTP and CBR application can be done through the following command
1. The first field is the event type. It is given by one of four possible symbols r, +, -, d which
correspond respectively to receive (at the output of the link), enqueued, dequeued and dropped.
2. The second field gives the time at which the event occurs.
3. Gives the input node of the link at which the event occurs.
4. Gives the output node of the link at which the event occurs.
5. Gives the packet type (e.g. CBR or TCP)
6. Gives the packet size
7. Some flags
8. This is the flow id (fid) of IPv6 that a user can set for each flow at the input OTcl script one can
further use this field for analysis purposes; it is also used when specifying stream color for the
NAM display.
Dept. of ECE, DSATM, B-82 Page 80
Computer Networks Lab Manual 18ECL78
XGRAPH
The Xgraph program draws a graph on an x-display given data read from either data file or from
standard input if no files are specified. It can display upto 64 independent data sets using different
colors and line styles for each set. It annotates the graph with a title, axis labels, grid lines or tick
marks, grid labels and a legend.
Syntax:
Xgraph [options] file-name
NAM
Nam is a Tcl/TK based animation tool for viewing network simulation traces and real world packet
traces. It supports topology layout, packet level animation, and various data inspection tools.
The Network Animator (nam) is a completely separate program that is distributed with the NS
simulator
This program is named nam and it shows the progression of the packets through the network.
The nam program reads an input file (containing the packet transmission events) and draw the
network events graphically.
Running NAM
nam is a UNIX program and it is run as a command line.Example:
UNIX>> nam nam.input
nam.input is the file that contains network events
The key to making the animation input file is to tell NS to output network events into a file for nam to
use.
Do the following:
2. Activate the NAM trace feature in NS before running the simulation (this will tell NS to write NAM
events outputs to the output file)
Then you can run nam with the output file (as input file for nam). Example:
Run the program using ns Reno1-nam.tcl; it will produce "out.nam" as output
When it finishes, run: nam out.nam to see the packets flow.
Awk- An Advanced
awk is a programmable, pattern-matching, and processing tool available in UNIX. Itworks equally well
with text and numbers.
awk is not just a command, but a programming language too. In other words, awk utility is a pattern
scanning and processing language. It searches one or more files to see if they contain lines that match
specified patterns and then perform associated actions, such as writing the line to the standard output or
incrementing a counter each time it finds a match.
Syntax:
awk option ‘selection_criteria {action}’ file(s)
Here, selection_criteria filters input and select lines for the action component to act upon. The
selection_criteria is enclosed within single quotes and the action within the curly braces. Both the
selection_criteria and action forms an awk program.
Example: $ awk „/manager/ {print}‟ emp.lst
Variables
Awk allows the user to use variables of there choice. You can now print a serial number, using the
variable kount, and apply it those directors drawing a salary exceeding 6700:
$ awk –F”|” „$3 == “director” && $6 > 6700 {
kount =kount+1
printf “ %3f %20s %-12s %d\n”, kount,$2,$3,$6 }‟ empn.lst
Observe that this time we haven‟t used quotes to enclose the awk program. You can now use
awk with the –f filename option to obtain the same output:
BUILT-IN VARIABLES
Awk has several built-in variables. They are all assigned automatically, though it is also possible for a
user to reassign some of them. You have already used NR, which signifies the record number of the
current line. We‟ll now have a brief look at some of the other variable.
The FS Variable: as stated elsewhere, awk uses a contiguous string of spaces as the default field
delimiter. FS redefines this field separator, which in the sample database happens to be the |. When
used at all, it must occur in the BEGIN section so that the body of the program knows its value before it
starts processing:
BEGIN {FS=”|”}
This is an alternative to the –F option which does the same thing.
The OFS Variable: when you used the print statement with comma-separated arguments, each
argument was separated from the other by a space. This is awk‟s default output field separator, and can
reassigned using the variable OFS in the BEGIN section:
BEGIN { OFS=”~” }
When you reassign this variable with a ~ (tilde), awk will use this character for delimiting the print
arguments. This is a useful variable for creating lines with delimited fields.
The NF variable: NF comes in quite handy for cleaning up a database of lines that don‟t contain the
right number of fields. By using it on a file, say emp.lst, you can locate those lines not having 6 fields,
and which have crept in due to faulty data entry:
$awk „BEGIN {FS = “|”}
NF! =6 {
Print “Record No “, NR, “has”, “fields”}‟ empx.lst
3) Now you need to download some essential packages for ns2,these packages can be downloaded by using
the following command : applications>accessories>terminal or dashhome>trminal
then type the below line on the terminal window
"sudo apt-get install autoconf automake gcc g++ build-essential libxmu-dev libtool libxt-dev"
4) Now change your directory(here i have already extracted the downloaded files to desktop,so my location
is desktop) type the following codes in the command window to install NS2.
cd Desktop
cd ns-allinone-2.35
./install
5) After compleating the installation type the following command in the command window
gedit ~/.bashrc
6) Now an editor window appears,please copy and paste the follwing codes in the end of the text file (note
that '/home/abhiram/Desktop/ns-allinone-2.35/octl-1.14' in each line in the below code should be replaced
with your location where the 'ns-allinone-2.35.tar.gz'file is extracted)
# LD_LIBRARY_PATH
OTCL_LIB=/home/abhiram/Desktop/ns-allinone-2.35/otcl-1.14
NS2_LIB=/home/abhiram/Desktop/ns-allinone-2.35/lib
X11_LIB=/usr/X11R6/lib
USR_LOCAL_LIB=/usr/local/lib
export
LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$OTCL_LIB:$NS2_LIB:$X11_LIB:$USR_LOCAL_LIB
# TCL_LIBRARY
TCL_LIB=/home/abhiram/Desktop/ns-allinone-2.35/tcl8.5.10/library
USR_LIB=/usr/lib
export TCL_LIBRARY=$TCL_LIB:$USR_LIB
# PATH
XGRAPH=/home/abhiram/Desktop/ns-allinone-2.35/bin:/home/abhiram/Desktop/ns-allinone-
2.35/tcl8.5.10/unix:/home/abhiram/Desktop/ns-allinone-2.35/tk8.5.10/unix
NS=/home/abhiram/Desktop/ns-allinone-2.35/ns-2.35/
NAM=/home/abhiram/Desktop/ns-allinone-2.35/nam-1.15/
PATH=$PATH:$XGRAPH:$NS:$NAM
7) Save and close the text editor and then type the following command on the terminal
source ~/.bashrc
8) Close the terminal window and start a new terminal window and now change the directory to ns-2.35 and
validate ns-2.35 by exicuting the following command ( it takes 30 to 45 minutes)
cd ns-2.35
./validate
9) If the installation is successful, then you will be able to see % at the command prompt while typing the
following command
ns
exit
ADD-ON PROGRAMS
N0 N4
P0 N2 N3 P2
N1 N5
P1 P3
The above wired network consists of 6 nodes (N0 to N5) and Nodes N0, N1, N4, N5 are connected to
ping agent, P0 will send message to P2 and P1 to P3, later P2 and P3 respond back to P0 and P1. This
trace of communication can be seen in lab7.tr file and to check congestion effect, the bandwidth and
queue size of link between N2 and N3 are reduced to 0.1Mb and 0/1.
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
#===================================
# Nodes Definition
#===================================
#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]
#===================================
# Links Definition
#===================================
#Create links 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 0.1Mb 10ms DropTail
$ns queue-limit $n2 $n3 0
$ns duplex-link $n3 $n4 100.0Mb 10ms DropTail
$ns queue-limit $n3 $n4 50
$ns duplex-link $n3 $n5 100.0Mb 10ms DropTail
$ns queue-limit $n3 $n5 50
#===================================
# Agents Definition
#===================================
#Create two ping agents and attach them to the nodes n0 and n2
set p0 [new Agent/Ping]
$ns attach-agent $n0 $p0
Dept. of ECE, DSATM, B-82 Page 90
Computer Networks Lab Manual 18ECL78
#Schedule events
$ns at 0.2 "$p0 send"
$ns at 0.2 "$p1 send"
$ns run
ns-Network Simulator
Step 3: Once the simulation is completed, run awk file to observe the output
2.Simulate a simple BSS with transmitting nodes in Wireless LAN and determine
the performance with respect to transmission of packets.
N0
N1 N3
tcp0 sink1
N2
ftp0
The group of two or more nodes connecting to one assess point (N0) is called Basic Service Set (BSS).
In this wireless topology, Node N1 and N3 act as source and destination.
#===================================
# Simulation parameters setup
#===================================
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
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
-channel $chan \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace ON \
-movementTrace ON
#===================================
# Nodes Definition
#===================================
#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
#===================================
# Agents Definition
#===================================
#Setup a TCP connection
Dept. of ECE, DSATM, B-82 Page 95
Computer Networks Lab Manual 18ECL78
}
{
if($1=="r"&&$3=="_3_"&&$4=="AGT"&&$7=="tcp"&&$8=="1540")
{
a++;
}
if($1=="s"&&$3=="_1_"&&$4=="AGT"&&$7=="tcp"&&$8=="1540")
{
b++;
}
if($1=="D"&&$3=="_0_"&&$4=="AGT"&&$7=="tcp"&&$8=="1540")
{
c++;
}
}
END{
printf("\n total number of packets drop: %d\n", c++);
printf("\n total number of packets sent: %d\n", b++);
printf("\n total number of packets received: %d\n", a++);
}
Steps for Execution
Step 1: Type the above program in text editor and save it with the filename and extension “.tcl”
ns-Network Simulator
Step 3: Once the simulation is completed, run awk file to observe the output
3.Simulate a network with star Topology (One router and several Hosts) Declare
Applications (TCP or UDP) to send packets from hosts and to receiver (on One
Host). Test the bandwidth and the Delay, When Buffers are of infinite capacities
and buffers are limited Capacities.
ftp0 sink3
tcp0 sink4
N0 N4
sink5
N3
ftp1 N1 N2
ftp2
tcp1
tcp2
#===================================
# Simulation parameters setup
#===================================
set val(stop) 10.0 ;# time of simulation end
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
#===================================
# Nodes Definition
#===================================
#Create 5 nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
set n4 [$ns node]
#===================================
# Links Definition
#===================================
#Createlinks between nodes
$ns duplex-link $n0 $n3 100.0Mb 10ms DropTail
$ns queue-limit $n0 $n3 50
$ns duplex-link $n1 $n3 100.0Mb 10ms DropTail
$ns queue-limit $n1 $n3 50
$ns duplex-link $n2 $n3 100.0Mb 10ms DropTail
$ns queue-limit $n2 $n3 50
$ns duplex-link $n3 $n4 100.0Mb 10ms DropTail
$ns queue-limit $n3 $n4 50
#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
#===================================
# Agents Definition
#===================================
#Setup a TCP connection
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set sink3 [new Agent/TCPSink]
Dept. of ECE, DSATM, B-82 Page 100
Computer Networks Lab Manual 18ECL78
#===================================
#Define a 'finish' procedure
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam lab9.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
BEGIN{
a=0
b=0
c=0
d=0
}
{
if($1=="r"&&$3=="0"&&$4=="3"&&$5=="tcp"&&$6=="1540")
{
a++;
}
if($1=="r"&&$3=="1"&&$4=="3"&&$5=="tcp"&&$6=="1540")
{
b++;
}
if($1=="r"&&$3=="2"&&$4=="3"&&$5=="tcp"&&$6=="1540")
{
c++;
}
if($1=="r"&&$3=="3"&&$4=="4"&&$5=="tcp"&&$6=="1540")
{
d++;
}
}
END{
printf("\n total number of packets received at Node 3 due to Node 0: %d\n", a++);
printf("\n total number of packets received at Node 3 due to Node 1: %d\n", b++);
printf("\n total number of packets received at Node 3 due to Node 2: %d\n", c++);
printf("\n total number of packets received at Node 4 due to host Nodes: %d\n", d++);
}
Simulation Result
2 500 30 30 810
3 700 10 50 390
4.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.
N0
sink2
tcp0
N2 N3
ftp0
null3
N1
udp1
cbr1
In this network topology there are two source nodes N0 and N1, they will be transmitting TCP and
UDP packets to destination node N3.
#===================================
# Simulation parameters setup
#===================================
set val(stop) 50.0 ;# time of simulation end
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
#===================================
# Nodes Definition
#===================================
#Create 4 nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
#===================================
# Links Definition
#===================================
#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
#===================================
# Agents Definition
#===================================
#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_ 50000
#===================================
# Applications Definition
#===================================
#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"
#===================================
# Termination
#===================================
#Define a 'finish' procedure
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam lab10.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
BEGIN{
a=0
b=0
}
{
if($1=="r"&&$3=="2"&&$4=="3"&&$5=="tcp"&&$6=="50040")
{
a++;
}
if($1=="r"&&$3=="2"&&$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++);
Dept. of ECE, DSATM, B-82 Page 107
Computer Networks Lab Manual 18ECL78
Simulation Result
Socket-Server.c
#`include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <sys/types.h>
int main(void)
{
int listenfd = 0,connfd = 0;
char sendBuff[1025];
int numrv;
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(5000);
while(1)
{
connfd = accept(listenfd, (struct sockaddr*)NULL ,NULL); // accept awaiting request
close(connfd);
sleep(1);
}
return 0;
}
Socket-client.c
#include <sys/socket.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <netdb.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <arpa/inet.h>
int main(void)
{
int sockfd = 0,n = 0;
char recvBuff[1024];
struct sockaddr_in serv_addr;
{
printf("\n Error : Could not create socket \n");
return 1;
}
serv_addr.sin_family = AF_INET;
serv_addr.sin_port = htons(5000);
serv_addr.sin_addr.s_addr = inet_addr("127.0.0.1");
if( n < 0)
{
printf("\n Read Error \n");
}
return 0;
}
4) What is a LAN?
LAN is short for Local Area Network. It refers to the connection between computers and other network
devices that are located within a small physical location.
5) What is a node?
A node refers to a point or joint where a connection takes place. It can be computer or device that is
part of a network. Two or more nodes are needed in order to form a network connection.
15) What is the job of the Network Layer under the OSI reference model?
The Network layer is responsible for data routing, packet switching and control of network congestion.
Routers operate under this layer.
16) How does a network topology affect your decision in setting up a network?
Network topology dictates what media you must use to interconnect devices. It also serves as basis on
what materials, connector and terminations that is applicable for the setup.
WAN stands for Wide Area Network. It is an interconnection of computers and devices that are
geographically dispersed. It connects networks that are located in different regions and countries.
23) What are proxy servers and how do they protect computer networks?
Proxy servers primarily prevent external users who identifying the IP addresses of an internal network.
Without knowledge of the correct IP address, even the physical location of the network cannot be
identified. Proxy servers can make a network virtually invisible to external users.
25) What is the importance of implementing a Fault Tolerance System? Are there
limitations?
A fault tolerance system ensures continuous data availability. This is done by eliminating a single point
of failure. However, this type of system would not be able to protect data in some cases, such as in
accidental deletions.
30) What is OSI and what role does it play in computer networks?
OSI (Open Systems Interconnect) serves as a reference model for data communication. It is made up of
7 layers, with each layer defining a particular aspect on how network devices connect and communicate
with one another. One layer may deal with the physical media used, while another layer dictates how
data is actually transmitted across the network.
31) What is the purpose of cables being shielded and having twisted pairs?
The main purpose of this is to prevent crosstalk. Crosstalks are electromagnetic interferences or noise
that can affect data being transmitted across cables.
34) What is the equivalent layer or layers of the TCP/IP Application layer in terms of OSI
reference model?
The TCP/IP Application layer actually has three counterparts on the OSI model: the Session layer,
Presentation Layer and Application Layer.
Gateways provide connectivity between two or more network segments. It is usually a computer that
runs the gateway software and provides translation services. This translation is a key in allowing
different systems to communicate on the network.
51) What protocol can be applied when you want to transfer files between different platforms,
such between UNIX systems and Windows servers?
Use FTP (File Transfer Protocol) for file transfers between such different servers. This is possible
because FTP is platform independent.
53) One way of securing a network is through the use of passwords. What can be considered as
good passwords?
Good passwords are made up of not just letters, but by combining letters and numbers. A password that
combines uppercase and lowercase letters is favorable than one that uses all upper case or all lower case
letters. Passwords must be not words that can easily be guessed by hackers, such as dates, names,
favorites, etc. Longer passwords are also better than short ones.
57) What happens when you use cables longer than the prescribed length?
Cables that are too long would result in signal loss. This means that data transmission and reception
would be affected, because the signal degrades over length.
63) What advantages does fiber optics have over other media?
One major advantage of fiber optics is that is it less susceptible to electrical interference. It also
supports higher bandwidth, meaning more data can be transmitted and received. Signal degrading is
also very minimal over long distances.
65) What are the different network protocols that are supported by Windows RRAS services?
There are three main network protocols supported: NetBEUI, TCP/IP, and IPX.
66) What are the maximum networks and hosts in a class A, B and C network?
For Class A, there are 126 possible networks and 16,777,214 hosts
For Class B, there are 16,384 possible networks and 65,534 hosts
For Class C, there are 2,097,152 possible networks and 254 hosts
68) What protocols fall under the Application layer of the TCP/IP stack?
The following are the protocols under TCP/IP Application layer: FTP, TFTP, Telnet and SMTP.
69) You need to connect two computers for file sharing. Is it possible to do this without using a
hub or router?
Yes, you can connect two computers together using only one cable. A crossover type cable can be use
in this scenario. In this setup, the data transmit pin of one cable is connected to the data receive pin of
the other cable, and vice versa.
Dept. of ECE, DSATM, B-82 Page 118
Computer Networks Lab Manual 18ECL78
74) When you move the NIC cards from one PC to another PC, does the MAC address gets
transferred as well?
Yes, that's because MAC addresses are hard-wired into the NIC circuitry, not the PC. This also means
that a PC can have a different MAC address when the NIC card was replace by another one.
76) In a network that contains two servers and twenty workstations, where is the best place to
install an Anti-virus program?
An anti-virus program must be installed on all servers and workstations to ensure protection. That's
because individual users can access any workstation and introduce a computer virus when plugging in
their removable hard drives or flash drives.
77) Describe Ethernet.
Ethernet is one of the popular networking technologies used these days. It was developed during the
early 1970s and is based on specifications as stated in the IEEE. Ethernet is used in local area networks.
SMTP is short for Simple Mail Transfer Protocol. This protocol deals with all Internal mail, and
provides the necessary mail delivery services on the TCP/IP protocol stack.
86) What are the different technologies involved in establishing WAN links?
Analog connections - using conventional telephone lines; Digital connections - using digitalgrade
telephone lines; switched connections - using multiple sets of links between sender and receiver to
move data.
90) How does dynamic host configuration protocol aid in network administration?
Instead of having to visit each client computer to configure a static IP address, the network
administrator can apply dynamic host configuration protocol to create a pool of IP addresses known as
scopes that can be dynamically assigned to clients.
REFERENCE