SlideShare una empresa de Scribd logo
1 de 64
SRINIVAS UNIVERSITY
COLLEGE OF ENGINEERING AND TECHNOLOGY
MUKKA – 574146
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
LAB MANUAL
ON
COMPUTER NETWORKS
Subject Code: 19SCSL56
2021-2022
Prepared by,
Ms. SHIFANA BEGUM
Assistant Professor, Dept of C S & E,
SUCET
Name
Section / Branch
Semester
USN
SRINIVAS UNIVERSITY
COLLEGE OF ENGINEERING AND TECHNOLOGY, MUKKA - 574146
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
Institution Vision
To transform society by imparting quality technical education in dynamic equilibrium with
social, ecological and economic environment, striving continuously for excellence in
education, research and technological service to the nation
Institution Mission
To provide knowledge based technological education to the students and train them as a
competent professional manpower with ethical values to fulfill the needs of the society and
industry by implementing the state-of the art education including technological innovation.
Vision of Department of Computer Science and Engineering
To impart state of the art technical education by providing conductive learning environment
for technological innovation, to inculcate research culture and skills necessary to meet the
changing needs of the industry and the society in the field of Computer Science and
Engineering and allied disciplines.
Mission of Department of Computer Science and Engineering
To be a centre of excellence in Computer Science and Engineering and to create qualified
Computer Science Engineers with a vision to take up the demanding challenges of the industry
and society in emerging fields of Computer Science and Engineering
Programme Educational Objectives (PEOs) of Department of Computer Science and
Engineering
1. To prepare students for successful careers in industry that meet the needs of Indian
and multinational companies with latest technical skills
2. To develop the ability among students to synthesize data and technical concepts for
application to product innovation, design & development and manufacturing.
3. To provide opportunity for students to work as part of teams on multidisciplinary
projects with communication skills
4. To provide students with a sound foundation in the mathematical, scientific and
engineering fundamentals necessary to formulate, solve and analyze engineering
problems.
5. To promote student awareness on lifelong learning and to introduce them to 7
professional ethics and codes of professional practice.
PROGRAM OUTCOMES (POs)
Engineering Graduates should possess the following:
1.Engineering knowledge: Apply the knowledge of mathematics, science, engineering
fundamentals, and an engineering specialization to the solution of complex engineering
problems.
2.Problem analysis: Identify, formulate, review 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 the specified needs with appropriate
consideration for the public health and safety, and the cultural, societal, and environmental
considerations.
4.Conduct investigations of complex problems: Use research-based knowledge and research
methods including design of experiments, analysis and interpretation of data, and synthesis of
the 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 understanding of the limitations.
6.The engineer and society: Apply reasoning informed by the contextual knowledge to assess
societal, health, safety, legal and cultural issues and the consequent responsibilities
relevant to the professional engineering practice.
7.Environment and sustainability: Understand the impact of the professional engineering
solutions in societal and environmental contexts, and demonstrate the knowledge of, and need
for sustainable development.
8.Ethics: Apply ethical principles and commit to professional ethics and responsibilities
and norms of the engineering practice.
9.Individual and team work: Function effectively as an individual, and as a member or
leader in diverse teams, and in multidisciplinary 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.Project management and finance: Demonstrate knowledge and understanding of the
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 multi-disciplinary environments.
12.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.
GENERAL LABORATORY INSTRUCTIONS:
1. Students are advised to come to the laboratory at least 5 minutes before (to starting
time), those who come after 5 minutes will not be allowed into the lab.
2. Plan your task properly much before to the commencement, come prepared to the lab
with the program / experiment details.
3. Student should enter into the laboratory with:
a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm,
Procedure, Program, Expected Output, etc.,) filled in for the lab session.
b. Laboratory Record updated up to the last session experiments and other utensils (if
any) needed in the lab.
c. Proper Dress code and Identity card.
4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer
system allotted to you by the faculty.
5. Execute your task in the laboratory, and record the results / output in the lab
observation note book, and get certified by the concerned faculty.
6. All the students should be polite and cooperative with the laboratory staff, must
maintain the discipline and decency in the laboratory.
8. Students / Faculty must keep their mobile phones in SILENT mode during the lab
sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract
severe punishment.
9. Students must take the permission of the faculty in case of any urgency to go out .
10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves
the lab after completing the task (experiment) in all aspects. He/she must ensure the system /
seat is kept properly.
Lab Incharge Head of the Department
COMPUTER NETWORKS LABORATORY
Course Code : 19SCSL56 IA Marks : 50
Hours/Week : 3 Exam Hours : 3
Credits : 2 Exam Marks : 50
Total Hours : 42
Course Objectives:
 Demonstrate operation of network and its management commands.
 Simulate and demonstrate the performance of GSM and CDMA.
 Implement data link layer and transport layer protocols.
Course Outcomes:
After studying this course, students will be able to:
CO1: Analyze and Compare various networking protocols.
CO2: Demonstrate the working of different concepts of networking.
CO3: Implement, analyze and evaluate networking protocols in NS2 / NS3.
Description (If any):
 For the experiments below modify the topology and parameters set for the experiment and
take multiple rounds of reading and analyze the results available in log files. Plot necessary
graphs and conclude. Use NS2/NS3.
Lab Experiments:
Part A
1. Implement three nodes point – to – point network with duplex links between them. Set the
queue size, vary the bandwidth and find the number of packets dropped.
2. Implement transmission of ping messages/trace route over a network topology consisting of 6
nodes and find the number of packets dropped due to congestion.
3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot congestion
window for different source / destination.
4. 4. Implement simple ESS and with transmitting nodes in wire-less LAN by simulation and
determine the performance with respect to transmission of packets.
5. Implement and study the performance of GSM on NS2/NS3 (Using MAC layer) or equivalent
environment. 6. Implement and study the performance of CDMA on NS2/NS3 (Using stack
called Call net) or equivalent environment.
Part B
Implement the following in Java:
1. Write a program for error detecting code using CRC-CCITT (16- bits).
2. Write a program to find the shortest path between vertices using bellman-ford algorithm.
3. Using TCP/IP sockets, write a client – server progr am to make the client send the file name and
to make the server send back the contents of the requested file if present.
4. Write a program on datagram socket for client/server to display the messages on client side, typed
at the server side.
5. Write a program for simple RSA algorithm to encrypt and decrypt the data.
6. Write a program for congestion control using leaky bucket algorithm.
Conduction of Practical Examination:
 All laboratory experiments from part A and part B are to be included for practical
examination.
 Students are allowed to pick one experiment from the lot.
 Strictly follow the instructions as printed on the cover page of answer script.
 Marks Distribution: Procedure+Conduction+Viva:12+28+10=50 Marks
 Change of experiment is allowed only once and marks allotted to the procedure part to be
made zero.
CONTENTS
SL
No.
Experiments
Page
No
Marks Remarks
Introduction to NS2 1-11
1
Implement three nodes point – to – point network with
duplex links between them. Set the queue size, vary the
bandwidth and find the number of packets dropped.
12-14
2
Implement transmission of ping messages/trace route over
a network topology consisting of 6 nodes and find the
number of packets dropped due to congestion.
15-19
3
Implement an Ethernet LAN using n nodes and set
multiple traffic nodes and plot congestion window for
different source / destination.
20-23
4
Implement simple ESS and with transmitting nodes in
wire-less LAN by simulation and determine the
performance with respect to transmission of packets.
24-27
5
Implement and study the performance of GSM on
NS2/NS3 (Using MAC layer) or equivalent environment.
28-30
6
Implement and study the performance of CDMA on
NS2/NS3 (Using stack called Call net) or equivalent
environment
31-34
7
Program for error detecting code using CRC-CCITT (16-
bits).
35-36
8 Program to find the shortest path between vertices using
bellman-ford algorithm.
37-40
9
Client – server program to make the client send the file
name and to make the server send back the contents of the
requested file if present.
41-44
10
Program on datagram socket for client/server to display the
messages on client side, typed at the server side.
45-48
11
Program for simple RSA algorithm to encrypt and decrypt
the data.
49-53
12
Program for congestion control using leaky bucket
algorithm.
54-55
Computer Networks Lab (19SCSL56)
Dept of C.S & E, SUCET ,MUKKA Page 1
Introduction to NS-2:
 Widely known as NS2, is simply an event driven simulation tool.
 Useful in studying the dynamic nature of communication networks.
 Simulation of wired as well as wireless network functions and protocols (e.g., routing
algorithms, TCP, UDP) can be done using NS2.
 In general, NS2 provides users with a way of specifying such network protocols and
simulating their corresponding behaviors.
Basic Architecture of NS2
Tcl scripting
• Tcl is a general purpose scripting language. [Interpreter]
• Tcl runs on most of the platforms such as Unix, Windows, and Mac.
• The strength of Tcl is its simplicity.
• It is not necessary to declare a data type for variable prior to the usage.
Basics of TCL
Syntax: command arg1 arg2 arg3
 Hello World!
puts stdout{Hello, World!}
Hello, World!
 Variables Command Substitution
set a 5 set len [string length foobar]
set b $a set len [expr [string length foobar] + 9]
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET, Mukka Page 2
Simple Arithmetic
expr 7.2 / 4
 Procedures
proc Diag {a b} {
set c [expr sqrt($a * $a + $b * $b)]
return $c }
puts “Diagonal of a 3, 4 right triangle is [Diag 3 4]”
Output: Diagonal of a 3, 4 right triangle is 5.0
 Loops
while{$i < $n} { for {set i 0} {$i < $n} {incr i} {
. . . . . .
} }
Wired TCL Script Components
Create the event scheduler
Open new files & turn on the tracing
Create the nodes
Setup the links
Configure the traffic type (e.g., TCP, UDP, etc)
Set the time of traffic generation (e.g., CBR, FTP)
Terminate the simulation
NS Simulator Preliminaries.
1. Initialization and termination aspects of the ns simulator.
2. Definition of network nodes, links, queues and topology.
3. Definition of agents and of applications.
4. The nam visualization tool.
5. Tracing and random variables.
Initialization and Termination of TCL Script in NS-2
An ns simulation starts with the command
Which is thus the first line in the tcl script? This line declares a new variable as using the set
command, you can call this variable as you wish, In general people declares it as ns because it
set ns [new Simulator]
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET, Mukka Page 3
is an instance of the Simulator class, so an object the code[new Simulator] is indeed the
installation of the class Simulator using the reserved word new.
In order to have output files with data on the simulation (trace files) or files used for
visualization (nam files), we need to create the files using “open” command:
#Open the Trace file
#Open the NAM trace file
The above creates a dta trace file called “out.tr” and a nam visualization trace file
called “out.nam”.Within the tcl script,these files are not called explicitly by their names,but
instead by pointers that are declared above and called “tracefile1” and “namfile”
respectively.Remark that they begins with a # symbol.The second line open the file “out.tr” to
be used for writing,declared with the letter “w”.The third line uses a simulator method called
trace-all that have as parameter the name of the file where the traces will go.
The last line tells the simulator to record all simulation traces in NAM input format.It
also gives the file name that the trace will be written to later by the command $ns flush-
trace.In our case,this will be the file pointed at by the pointer “$namfile”,i.e the file “out.tr”.
The termination of the program is done using a “finish” procedure.
#Define a „finish‟ procedure
Proc finish { } {
global ns tracefile1 namfile
$ns flush-trace
Close $tracefile1
Close $namfile
Exec nam out.nam &
Exit 0
}
set tracefile1 [open out.tr w]
$ns trace-all $tracefile1
set namfile [open out.nam w]
$ns namtrace-all $namfile
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET, Mukka Page 4
$ns duplex-link $n0 $n2 10Mb 10ms DropTail
$ns at 125.0 “finish”
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,
will be used to call “finish” at time 125sec.Indeed,the at method of the simulator allows us to
schedule events explicitly.
The simulation can then begin using the command
Definition of a network of links and nodes
The way to define a node is
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:
Which means that $n0 and $n2 are connected using a bi-directional link that has 10ms
of propagation delay and a capacity of 10Mb per sec for each direction.
To define a directional link instead of a bi-directional one, we should replace “duplex-
link” by “simplex-link”.
In NS, an output queue of a node is implemented as a part of each link whose input is
that node. The definition of the link then includes the way to handle overflow at that queue.
In our case, if the buffer capacity of the output queue is exceeded then the last packet to
$ns run
set n0 [$ns node]
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET, Mukka Page 5
set sink [new Agent /TCPSink]
#set Queue Size of link (n0-n2) to 20
$ns queue-limit $n0 $n2 20
arrive is dropped. Many alternative options exist, such as the RED (Random Early Discard)
mechanism, the FQ (Fair Queuing), the DRR (Deficit Round Robin), the stochastic Fair
Queuing (SFQ) and the CBQ (which including a priority and a round-robin scheduler).
Dept of ISE, CIT, Gubbi
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:
Agents and Applications
We need to define routing (sources, destinations) the agents (protocols) the
application that use them.
FTP over TCP
TCP is a dynamic reliable congestion control protocol. It uses Acknowledgements
created by the destination to know whether packets are well received.
There are number variants of the TCP protocol, such as Tahoe, Reno, NewReno,
Vegas. The type of agent appears in the first line:
The command $ns attach-agent $n0 $tcp defines the source node of the tcp connection.
The command
Defines the behavior of the destination node of TCP and assigns to it a pointer called sink.
set tcp [new Agent/TCP]
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET, Mukka Page 6
#Setup a UDP connection
#setup a CBR over UDP connection
The below shows the definition of a CBR application using a UDP agent
The command $ns attach-agent $n4 $sink defines the destination node. The
command $ns connect $tcp $sink finally makes the TCP connection between the source and
destination nodes.
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.
set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n5 $null
$ns connect $udp $null
$udp set fid_2
set cbr [new
Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set packetsize_ 100
$cbr set rate_ 0.01Mb
$cbr set random_ false
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET, Mukka Page 7
CBR over UDP
A UDP source and destination is defined in a similar way as in the case of TCP.
Instead of defining the rate in the command $cbr set rate_ 0.01Mb, one can define the
time interval between transmission of packets using the command.
The packet size can be set to some value using
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:
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
Structure of Trace Files
When tracing into an output ASCII file, the trace is organized in 12 fields as follows
in fig shown below, The meaning of the fields are:
Event Time From
Node
To
Node
PKT
Type
PKT
Size
Flags Fid Src
Addr
Dest
Addr
Seq
Num
Pkt
id
$cbr set interval_ 0.005
$cbr set packetSize_ <packet size>
$ns at <time> <event>
$ns at 0.1 “$cbr start”
$ns at 1.0 “ $ftp start”
$ns at 124.0 “$ftp stop”
$ns at 124.5 “$cbr stop”
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET, Mukka Page 8
1. The first field is the event type. It is given by one of four possible symbols r, +, -, d which
correspond respectively to receive (at the output of the link), enqueued, dequeued and
dropped.
2. The second field gives the time at which the event occurs.
3. Gives the input node of the link at which the event occurs.
4. Gives the output node of the link at which the event occurs.
5. Gives the packet type (eg CBR or TCP)
6. Gives the packet size
7. Some flags
8. This is the flow id (fid) of IPv6 that a user can set for each flow at the input OTcl script
one can further use this field for analysis purposes; it is also used when specifying stream
color for the NAM display.
9. This is the source address given in the form of “node.port”.
10. This is the destination address, given in the same form.
11. This is the network layer protocol’s packet sequence number. Even though UDP
implementations in a real network do not use sequence number, ns keeps track of UDP
packet sequence number for analysis purposes
12. The last field shows the Unique id of the packet.
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:
Options are listed here
/-bd <color> (Border)
This specifies the border color of the xgraph window.
/-bg <color> (Background)
This specifies the background color of the xgraph window.
Xgraph [options] file-name
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET, Mukka Page 9
/-fg<color> (Foreground)
This specifies the foreground color of the xgraph window.
/-lf <fontname> (LabelFont)
All axis labels and grid labels are drawn using this font.
/-t<string> (Title Text)
This string is centered at the top of the graph.
/-x <unit name> (XunitText)
This is the unit name for the x-axis. Its default is “X”.
/-y <unit name> (YunitText)
This is the unit name for the y-axis. Its default is “Y”.
Awk- An Advanced
awk is a programmable, pattern-matching, and processing tool available in UNIX. It
works equally well with text and numbers.
awk is not just a command, but a programming language too. In other words, awk
utility is a pattern scanning and processing language. It searches one or more files to see if
they contain lines that match specified patterns and then perform associated actions, such as
writing the line to the standard output or incrementing a counter each time it finds a match.
Syntax:
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
awk option ‘selection_criteria {action}’ file(s)
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET, Mukka Page 10
printf “ %3f %20s %-12s %dn”, kount,$2,$3,$6 }‟ empn.lst
THE –f OPTION: STORING awk PROGRAMS IN A FILE
You should holds large awk programs in separate file and provide them with the awk
extension for easier identification. Let’s first store the previous program in the file
empawk.awk:
$ cat empawk.awk
Observe that this time we haven’t used quotes to enclose the awk program. You can
now use awk with the –f filename option to obtain the same output:
THE BEGIN AND END SECTIONS
Awk statements are usually applied to all lines selected by the address, and if there are
no addresses, then they are applied to every line of input. But, if you have to print something
before processing the first line, for example, a heading, then the BEGIN section can be used
gainfully. Similarly, the end section useful in printing some totals after processing is over.
The BEGIN and END sections are optional and take the form
BEGIN {action}
END {action}
These two sections, when present, are delimited by the body of the awk program. You
can use them to print a suitable heading at the beginning and the average salary at the end.
BUILT-IN VARIABLES
Awk has several built-in variables. They are all assigned automatically, though it is
also possible for a user to reassign some of them. You have already used NR, which signifies
the record number of the current line. We’ll now have a brief look at some of the other
variable.
The FS Variable: as stated elsewhere, awk uses a contiguous string of spaces as the default
field delimiter. FS redefines this field separator, which in the sample database happens to be
the |. When used at all, it must occur in the BEGIN section so that the body of the program
knows its value before it starts processing:
BEGIN {FS=”|”}
This is an alternative to the –F option which does the same thing.
Awk –F”|” –f empawk.awk empn.lst
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 11
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
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 12
Part-A
Experiment No: 1
Aim: Simulate a three node point to point network with duplex links between them. Set queue
size and vary the bandwidth and find number of packets dropped.
Program:
set ns [new Simulator] # Letter S is capital
set nf [open PA1.nam w] # open a nam trace file in write mode
$ns namtrace-all $nf # nf nam filename
set tf [open PA1.tr w] # tf trace filename
$ns trace-all $tf
proc finish { } {
global ns nf tf
$ns flush-trace # clears trace file contents
close $nf
close $tf
exec nam PA1.nam &
exit 0
}
set n0 [$ns node] # creates 3 nodes
set n2 [$ns node]
set n3 [$ns node]
$ns duplex-link $n0 $n2 200Mb 10ms DropTail # establishing links
$ns duplex-link $n2 $n3 1Mb 1000ms DropTail
$ns queue-limit $n0 $n2 10
set udp0 [new Agent/UDP] # attaching transport layer protocols
$ns attach-agent $n0 $udp0
set cbr0 [new Application/Traffic/CBR] # attaching application layer protocols
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent $udp0
set null0 [new Agent/Null] # creating sink(destination) node
$ns attach-agent $n3 $null0
$ns connect $udp0 $null0
$ns at 0.1 "$cbr0 start"
$ns at 1.0 "finish"
$ns run
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 13
AWK file: (Open a new editor using “vi command” and write awk file and save with “.awk”
extension)
#immediately after BEGIN should open braces „{„
BEGIN{ c=0;}
{
if($1= ="d")
{ c++;
printf("%st%sn",$5,$11);
}
}
END{ printf("The number of packets dropped =%dn",c); }
Steps for execution:
 Open vi editor and type program. Program name should have the extension “ .tcl ”
[root@localhost ~]# vi lab1.tcl
 Save the program by pressing “ESC key” first, followed by “Shift and :” keys simultaneously
and type “wq” and press Enter key.
 Open vi editor and type awk program. Program name should have the extension “.awk ”
[root@localhost ~]# vi lab1.awk
 Save the program by pressing “ESC key” first, followed by “Shift and :” keys simultaneously
and type “wq” and press Enter key.
 Run the simulation program
[root@localhost~]# ns lab1.tcl
 Here “ns” indicates network simulator. We get the topology shown in the snapshot.
 Now press the play button in the simulation window and the simulation will begins.
 After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f lab1.awk lab1.tr
 To see the trace file contents open the file as ,
[root@localhost~]# vi lab1.tr
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
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 14
Contents of Trace File Topology
Output
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 15
Experiment No:2
Aim: Implement transmission of ping messages/trace route over a network topology
consisting of 6 nodes and find the number of packets dropped due to congestion.
Program:
set ns [ new Simulator ]
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
$ns queue-limit $n0 $n4 5
$ns queue-limit $n2 $n4 3
$ns queue-limit $n4 $n5 2
Agent/Ping instproc recv {from rtt} {
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 16
$self instvar node_
puts "node [$nod e_ 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"
$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"
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 17
$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
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 =%dn",$5,drop);
}
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 18
Steps for execution
1) Open vi editor and type program. Program name should have the extension “ .tcl ”
[root@localhost ~]# vi lab4.tcl
2) Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enter key.
3) Open vi editor and type awk program. Program name should have the extension
“.awk ”
[root@localhost ~]# vi lab4.awk
4) Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enter key.
5) Run the simulation program
[root@localhost~]# ns lab4.tcl
i) Here “ns” indicates network simulator. We get the topology shown in the
snapshot.
ii) Now press the play button in the simulation window and the simulation
will begins.
6) After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f lab4.awk lab4.tr
7) To see the trace file contents open the file as ,
[root@localhost~]# vi lab4.tr
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 19
Topology Output
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 20
Experiment No:3
Aim: Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot
congestion window for different source / destination.
Program:
set ns [new Simulator]
set tf [open pgm7.tr w]
$ns trace-all $tf
set nf [open pgm7.nam w]
$ns namtrace-all $nf
set n0 [$ns node]
$n0 color "magenta"
$n0 label "src1"
set n1 [$ns node]
set n2 [$ns node]
$n2 color "magenta"
$n2 label "src2"
set n3 [$ns node]
$n3 color "blue"
$n3 label "dest2"
set n4 [$ns node]
set n5 [$ns node]
$n5 color "blue"
$n5 label "dest1"
$ns make-lan "$n0 $n1 $n2 $n3 $n4" 100Mb 100ms LL Queue/ DropTail Mac/802_3 #
should come in single line
$ns duplex-link $n4 $n5 1Mb 1ms DropTail
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
$ftp0 set packetSize_ 500
$ftp0 set interval_ 0.0001
set sink5 [new Agent/TCPSink]
$ns attach-agent $n5 $sink5
$ns connect $tcp0 $sink5
set tcp2 [new Agent/TCP]
$ns attach-agent $n2 $tcp2
set ftp2 [new Application/FTP]
$ftp2 attach-agent $tcp2
$ftp2 set packetSize_ 600
$ftp2 set interval_ 0.001
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 21
set sink3 [new Agent/TCPSink]
$ns attach-agent $n3 $sink3
$ns connect $tcp2 $sink3
set file1 [open file1.tr w]
$tcp0 attach $file1
set file2 [open file2.tr w]
$tcp2 attach $file2
$tcp0 trace cwnd_ # must put underscore ( _ ) after cwnd and no space between them
$tcp2 trace cwnd_
proc finish { } {
global ns nf tf
$ns flush-trace
close $tf
close $nf
exec nam pgm7.nam &
exit 0
}
$ns at 0.1 "$ftp0 start"
$ns at 5 "$ftp0 stop"
$ns at 7 "$ftp0 start"
$ns at 0.2 "$ftp2 start"
$ns at 8 "$ftp2 stop"
$ns at 14 "$ftp0 stop"
$ns at 10 "$ftp2 start"
$ns at 15 "$ftp2 stop"
$ns at 16 "finish"
$ns run
AWK file: (Open a new editor using “vi command” and write awk file and save with “.awk”
extension)
cwnd:- means congestion window
BEGIN {
}
{
if($6= ="cwnd_") # don‟t leave space after writing cwnd_
printf("%ft%ftn",$1,$7); # you must put n in printf
}
END {
}
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 22
Steps for execution:
1) Open vi editor and type program. Program name should have the extension “ .tcl ”
[root@localhost ~]# vi lab7.tcl
2) Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enter key.
3) Open vi editor and type awk program. Program name should have the extension
“.awk ”
[root@localhost ~]# vi lab7.awk
4) Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enter key.
5) Run the simulation program
[root@localhost~]# ns lab7.tcl
6) After simulation is completed run awk file to see the output ,
i. [root@localhost~]# awk –f lab7.awk file1.tr > a1
ii. [root@localhost~]# awk –f lab7.awk file2.tr > a2
iii. [root@localhost~]# xgraph a1 a2
7) Here we are using the congestion window trace files i.e. file1.tr and file2.tr and we
are redirecting the contents of those files to new files say a1 and a2 using output
redirection operator (>).
8) To see the trace file contents open the file as ,
[root@localhost~]# vi lab7.tr
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 23
Output
Graph
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 24
Experiment No:4
Aim: Implement simple ESS and with transmitting nodes in wire-less LAN by simulation
and determine the performance with respect to transmission of packets.
Program:
set ns [new Simulator]
set tf [open lab8.tr w]
$ns trace-all $tf
set topo [new Topography]
$topo load_flatgrid 1000 1000
set nf [open lab8.nam w]
$ns namtrace-all-wireless $nf 1000 1000
$ns node-config -adhocRouting DSDV 
-llType LL 
-macType Mac/802_11 
-ifqType Queue/DropTail 
-ifqLen 50 
-phyType Phy/WirelessPhy 
-channelType Channel/WirelessChannel 
-prrootype Propagation/TwoRayGround 
-antType Antenna/OmniAntenna 
-topoInstance $topo 
-agentTrace ON 
-routerTrace ON
create-god 3
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
$n0 label "tcp0"
$n1 label "sink1/tcp1"
$n2 label "sink2"
$n0 set X_ 50
$n0 set Y_ 50
$n0 set Z_ 0
$n1 set X_ 100
$n1 set Y_ 100
$n1 set Z_ 0
$n2 set X_ 600
$n2 set Y_ 600
$n2 set Z_ 0
$ns at 0.1 "$n0 setdest 50 50 15"
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 25
$ns at 0.1 "$n1 setdest 100 100 25"
$ns at 0.1 "$n2 setdest 600 600 25"
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
set sink1 [new Agent/TCPSink]
$ns attach-agent $n1 $sink1
$ns connect $tcp0 $sink1
set tcp1 [new Agent/TCP]
$ns attach-agent $n1 $tcp1
set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp1
set sink2 [new Agent/TCPSink]
$ns attach-agent $n2 $sink2
$ns connect $tcp1 $sink2
$ns at 5 "$ftp0 start"
$ns at 5 "$ftp1 start"
$ns at 100 "$n1 setdest 550 550 15"
$ns at 190 "$n1 setdest 70 70 15"
proc finish { } {
global ns nf tf
$ns flush-trace
exec nam lab8.nam &
close $tf
exit 0
}
$ns at 250 "finish"
$ns run
AWK file: (Open a new editor using “vi command” and write awk file and save with
“.awk” extension)
BEGIN{
count1=0
count2=0
pack1=0
pack2=0
time1=0
time2=0
}
{ if($1= ="r"&& $3= ="_1_" && $4= ="AGT")
{ count1++
pack1=pack1+$8
time1=$2 }
if($1= ="r" && $3= ="_2_" && $4= ="AGT")
{ count2++
pack2=pack2+$8
time2=$2 }
}
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 26
END{
printf("The Throughput from n0 to n1: %f Mbps n”,
((count1*pack1*8)/(time1*1000000)));
printf("The Throughput from n1 to n2: %f Mbps",
((count2*pack2*8)/(time2*1000000)));
}
Steps for execution
Open vi editor and type program. Program name should have the extension “ .tcl
”
[root@localhost ~]# vi lab8.tcl
Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enter key.
Open vi editor and type awk program. Program name should have the extension
“.awk ”
[root@localhost ~]# vi lab8.awk
Save the program by pressing “ESC key” first, followed by “Shift and :” keys
simultaneously and type “wq” and press Enter key.
Run the simulation program
[root@localhost~]# ns lab8.tcl
o Here “ns” indicates network simulator. We get the topology shown in the
snapshot.
o Now press the play button in the simulation window and the simulation will
begins.
After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f lab8.awk lab8.tr
To see the trace file contents open the file as ,
[root@localhost~]# vi lab8.tr
Topology:
Node 1 and 2 are communicating Node 2 is moving towards node 3
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 27
Node 2 is coming back from node 3 towards node1
Trace File
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 28
Experiment No:5
Aim: Implement and study the performance of GSM on NS2/NS3 (Using MAC layer) or equivalent environment.
Source Code:
# General Parameters
set stop 100 ;# Stop time.
# Topology
set type gsm ;#type of link:
# AQM parameters
set minth 30 ;
set maxth 0 ;
set adaptive 1 ;# 1 for Adaptive RED, 0 for plain RED
# Traffic generation.
set flows 0 ;# number of long-lived TCP flows
set window 30 ;# window for long-lived traffic
set web 2 ;# number of web sessions
# Plotting statics.
set opt(wrap) 100 ;# wrap plots?
set opt(srcTrace) is ;# where to plot traffic
set opt(dstTrace) bs2;# where to plot traffic
#default downlink bandwidth in bps
set bwDL(gsm) 9600
#default uplink bandwidth in bps
set bwUL(gsm) 9600
#default downlink propagation delay in seconds
set propDL(gsm) .500
#default uplink propagation delay in seconds
set propUL(gsm) .500
set ns [new Simulator]
set tf [open out.tr w]
$ns trace-all $t
set nodes(is) [$ns node]
set nodes(ms) [$ns node]
set nodes(bs1) [$ns node]
set nodes(bs2) [$ns node]
set nodes(lp) [$ns node]
proc cell_topo {} {
global ns nodes
$ns duplex-link $nodes(lp) $nodes(bs1) 3Mbps 10nodes(ms) DropTail
$ns duplex-link $nodes(bs1) $nodes(ms) 1 1 RED
$ns duplex-link $nodes(ms) $nodes(bs2) 1 1 RED
$ns duplex-link $nodes(bs2) $nodes(is) 3Mbps 50nodes(ms) DropTail
puts " GSM Cell Topology"
}
proc set_link_para {t} {
global ns nodes bwUL bwDL propUL propDL buf
$ns bandwidth $nodes(bs1) $nodes(ms) $bwDL($t) duplex
$ns bandwidth $nodes(bs2) $nodes(ms) $bwDL($t) duplex
$ns delay $nodes(bs1) $nodes(ms) $propDL($t) duplex
$ns delay $nodes(bs2) $nodes(ms) $propDL($t) duplex
$ns queue-limit $nodes(bs1) $nodes(ms) 10
$ns queue-limit $nodes(bs2) $nodes(ms) 10
}
# RED and TCP parameters
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 29
Queue/RED set adaptive_ $adaptive
Queue/RED set thresh_ $minth
Queue/RED set maxthresh_ $maxth
Agent/TCP set window_ $window
source web.tcl
#Create topology
switch $type {
gsm -
gprs -
umts {cell_topo}
}
set_link_para $type
$ns insert-delayer $nodes(ms) $nodes(bs1) [new Delayer]
$ns insert-delayer $nodes(ms) $nodes(bs2) [new Delayer]
# Set up forward TCP connection
if {$flows == 0} {
set tcp1 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp)
0]
set ftp1 [[set tcp1] attach-app FTP]
$ns at 0.8 "[set ftp1] start"
}
if {$flows > 0} {
set tcp1 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp) 0]
set ftp1 [[set tcp1] attach-app FTP]
$tcp1 set window_ 100
$ns at 0.0 "[set ftp1] start"
$ns at 3.5 "[set ftp1] stop"
set tcp2 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp) 0]
set ftp2 [[set tcp2] attach-app FTP]
$tcp2 set window_ 3
$ns at 1.0 "[set ftp2] start"
$ns at 8.0 "[set ftp2] stop"
}
proc stop {} {
global nodes opt nf
set wrap $opt(wrap)
set sid [$nodes($opt(srcTrace)) id]
set did [$nodes($opt(dstTrace)) id]
set a "out.tr"
set GETRC "../../../bin/getrc"
set RAW2XG "../../../bin/raw2xg"
exec $GETRC -s $sid -d $did -f 0 out.tr | 
$RAW2XG -s 0.01 -m $wrap -r > plot.xgr
exec $GETRC -s $did -d $sid -f 0 out.tr | 
$RAW2XG -a -s 0.01 -m $wrap >> plot.xgr
exec xgraph -x time -y packets plot.xgr &
exit 0
}
$ns at $stop "stop"
$ns run
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 30
Output: ns lab5.tcl
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 31
Experiment No: 6
Aim:Implement and study the performance of CDMA on NS2/NS3 (Using stack called Call net) or equivalent
environment.
PERFORMANCE OF CDMA
Source Code:
# General Parameters
set stop 100 ;# Stop time.
# Topology
set type cdma ;#type of link:
# AQM parameters
set minth 30 ;
set maxth 0 ;
set adaptive 1 ;# 1 for Adaptive RED, 0 for plain RED
# Traffic generation.
set flows 0 ;# number of long-lived TCP flows
set window 30 ;# window for long-lived traffic
set web 2 ;# number of web sessions
# Plotting statics.
set opt(wrap) 100 ;# wrap plots?
set opt(srcTrace) is ;# where to plot traffic
set opt(dstTrace) bs2;# where to plot traffic
#default downlink bandwidth in bps
set bwDL(cdma) 384000
#default uplink bandwidth in bps
set bwUL(cdma) 64000
#default downlink propagation delay in seconds
set propDL(cdma) .150
#default uplink propagation delay in seconds
set propUL(cdma) .150
set ns [new Simulator]
set tf [open out.tr w]
$ns trace-all $tf
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 32
set nodes(is) [$ns node]
set nodes(ms) [$ns node]
set nodes(bs1) [$ns node]
set nodes(bs2) [$ns node]
set nodes(lp) [$ns node]
proc cell_topo {} {
global ns nodes
$ns duplex-link $nodes(lp) $nodes(bs1) 3Mbps 10nodes(ms) DropTail
$ns duplex-link $nodes(bs1) $nodes(ms) 1 1 RED
$ns duplex-link $nodes(ms) $nodes(bs2) 1 1 RED
$ns duplex-link $nodes(bs2) $nodes(is) 3Mbps 50nodes(ms) DropTail
puts " cdma Cell Topology"
}
proc set_link_para {t} {
global ns nodes bwUL bwDL propUL propDL buf
$ns bandwidth $nodes(bs1) $nodes(ms) $bwDL($t) duplex
$ns bandwidth $nodes(bs2) $nodes(ms) $bwDL($t) duplex
$ns delay $nodes(bs1) $nodes(ms) $propDL($t) duplex
$ns delay $nodes(bs2) $nodes(ms) $propDL($t) duplex
$ns queue-limit $nodes(bs1) $nodes(ms) 20
$ns queue-limit $nodes(bs2) $nodes(ms) 20
}
# RED and TCP parameters
Queue/RED set adaptive_ $adaptive
Queue/RED set thresh_ $minth
Queue/RED set maxthresh_ $maxth
Agent/TCP set window_ $window
source web.tcl
#Create topology
switch $type {
cdma {cell_topo}
}
set_link_para $type
$ns insert-delayer $nodes(ms) $nodes(bs1) [new Delayer]
$ns insert-delayer $nodes(ms) $nodes(bs2) [new Delayer]
# Set up forward TCP connection
if {$flows == 0} {
set tcp1 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp) 0]
set ftp1 [[set tcp1] attach-app FTP]
$ns at 0.8 "[set ftp1] start"
}
if {$flows > 0} {
set tcp1 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp) 0]
set ftp1 [[set tcp1] attach-app FTP]
$tcp1 set window_ 100
$ns at 0.0 "[set ftp1] start"
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 33
$ns at 3.5 "[set ftp1] stop"
set tcp2 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp) 0]
set ftp2 [[set tcp2] attach-app FTP]
$tcp2 set window_ 3
$ns at 1.0 "[set ftp2] start"
$ns at 8.0 "[set ftp2] stop"
}
proc stop { } {
global
nodes opt
nf set
wrap
$opt(wra
p)
set sid
[$nodes($opt(srcTrace))
id] set did
[$nodes($opt(dstTrace))
id]set a "out.tr"
set GETRC "../../../bin/getrc"
set RAW2XG "../../../bin/raw2xg"
exec $GETRC -s $sid -d $did -f 0 out.tr | 
$RAW2XG -s 0.01 -m $wrap -r
> plot.xgrexec $GETRC -s $did -
d $sid -f 0 out.tr | 
$RAW2XG -a -s 0.01 -m $wrap
>> plot.xgrexec xgraph -x time -y
packets plot.xgr &
exit 0
}
$ns at $stop "stop"
$ns run
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 34
Output: ns lab6.tcl
CDMA TRACE FILE
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 35
Part B
7. Write a program for error detecting code using CRC-CCITT (16- bits).
import java.util.Scanner;
class CRC
{
public static void main(String args[])
{
Scanner sc=new Scanner(System.in);
int m,g[],n,d[],z[],r[],msb,i,j,k;
System.out.print(“Enter no. of data bits : “);
n=sc.nextInt();
System.out.print(“Enter no. of generator bits : “);
m=sc.nextInt();
d=new int[n+m];
g=new int[m];
System.out.print(“Enter data bits : “);
for(i=0;i<n;i++)
d[i]=sc.nextInt();
System.out.print(“Enter generator bits : “);
for(j=0;j<m;j++)
g[j]=sc.nextInt();
for(i=0;i<m-1;i++)
d[n+i]=0;
r=new int[m+n];
for(i=0;i<m;i++)
r[i]=d[i];
z=new int[m];
for(i=0;i<m;i++)
z[i]=0;
for(i=0;i<n;i++)
{
k=0;
msb=r[i];
for(j=i;j<m+i;j++)
{
if(msb==0)
r[j]=xor(r[j],z[k]);
else
r[j]=xor(r[j],g[k]);
k++;
}
r[m+i]=d[m+i];
}
System.out.print(“The code bits added are : “);
for(i=n;i<n+m-1;i++)
{
d[i]=r[i];
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 36
System.out.print(d[i]);
}
System.out.print(“nThe code data is : “);
for(i=0;i<n+m-1;i++)
{
System.out.print(d[i]);
}
}
public static int xor(int x,int y)
{
if(x==y)
return(0);
else
return(1);
}
}
/*Output of crc cyclic redundancy check program:
Enter no. of data bits : 14
Enter no. of generator bits : 4
Enter data bits : 1
1
0
1
0
0
1
1
1
0
1
1
0
0
Enter generator bits :
1
0
1
1
The code bits added are : 100
The code data is : 11010011101100100
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 37
8. Write a program to find the shortest path between vertices using bellman-ford algorithm.
This is a java program to find shortest path from a single vertex. The Bellman–Ford algorithm
is an algorithm that computes shortest paths from a single source vertex to all of the other
vertices in a weighted digraph.[1] It is slower than Dijkstra’s algorithm for the same problem,
but more versatile, as it is capable of handling graphs in which some of the edge weights are
negative numbers.
Here is the source code of the Java Program to Use the Bellman-Ford Algorithm to Find the
Shortest Path Between Two Vertices Assuming that Negative Size Edges Exist in the Graph.
The Java program is successfully compiled and run on a Windows system. The program
output is also shown below.
1.
2. package com.hinguapps.graph;
3.
4. import java.util.Scanner;
5.
6. public class BellmanFord
7. {
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
private int
private int
distances[];
numberofvertices;
public static final int MAX_VALUE = 999;
public BellmanFord(int numberofvertices)
{
this.numberofvertices = numberofvertices;
distances = new int[numberofvertices + 1];
}
public void
destination,
BellmanFordEvaluation(int source, int
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
int adjacencymatrix[][])
{
for (int node = 1; node <= numberofvertices; node++)
{
distances[node] = MAX_VALUE;
}
distances[source] = 0;
for (int node = 1; node <= numberofvertices - 1; node++)
{
for (int sourcenode = 1; sourcenode <=
numberofvertices; sourcenode++)
29. {
30. for (int destinationnode = 1; destinationnode <=
numberofvertices; destinationnode++)
31. {
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 38
32. if
(adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE)
33. {
34. if (distances[destinationnode] >
distances[sourcenode]
35. +
adjacencymatrix[sourcenode][destinationnode])
36. distances[destinationnode] =
distances[sourcenode]
37. +
adjacencymatrix[sourcenode][destinationnode];
38. }
39. }
40. }
41. }
42. for (int sourcenode = 1; sourcenode <= numberofvertices;
sourcenode++)
43. {
44. for (int destinationnode = 1; destinationnode <=
numberofvertices; destinationnode++)
45. {
46. if (adjacencymatrix[sourcenode][destinationnode]
!= MAX_VALUE)
47.
48.
{
if (distances[destinationnode] >
distances[sourcenode]
49.
50.
51.
+
adjacencymatrix[sourcenode][destinationnode])
System.out
.println("The
negative egde cycle");
}
}
}
Graph contains
52.
53.
54.
55. for (int vertex = 1; vertex <= numberofvertices;
vertex++)
56.
57.
58.
{
if (vertex == destination)
System.out.println("distance of source " +
source + " to "
59.
60.
61.
62.
63.
+ vertex + " is " + distances[vertex]);
}
}
public static void main(String... arg)
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 39
64. {
65. int numberofvertices = 0;
66. int source, destination;
67. Scanner scanner = new Scanner(System.in);
68. System.out.println("Enter the number of vertices");
69. numberofvertices = scanner.nextInt();
70. int adjacencymatrix[][] = new int[numberofvertices +
1][numberofvertices + 1];
71. System.out.println("Enter the adjacency matrix");
72. for (int sourcenode = 1; sourcenode <= numberofvertices;sourcenode++)
73. {
74. for (int destinationnode = 1; destinationnode <=
numberofvertices; destinationnode++)
75. {
76. adjacencymatrix[sourcenode][destinationnode] =
scanner
77. .nextInt();
78. if (sourcenode == destinationnode)
79. {
80. adjacencymatrix[sourcenode][destinationnode]
= 0;
81. continue;
82. }
83. if (adjacencymatrix[sourcenode][destinationnode]
== 0)
84. {
85. adjacencymatrix[sourcenode][destinationnode]
= MAX_VALUE;
86. }
87. }
88. }
89. System.out.println("Enter the source vertex");
90. source = scanner.nextInt();
91. System.out.println("Enter the destination vertex: ");
92. destination = scanner.nextInt();
93. BellmanFord bellmanford = new
BellmanFord(numberofvertices);
94. bellmanford.BellmanFordEvaluation(source, destination,
adjacencymatrix);
95. scanner.close();
96. }
97. }
Output:
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 40
$ javac BellmanFord.java
$ java BellmanFord
Output:
Enter the number of vertices
6
Enter the adjacency matrix
0 4 0 0 -1 0
0 0 -1 0 -2 0
Enter the source vertex
1
Enter the destination vertex:
4
distance of source 1 to 4 is -6
0 0 0 0 0 0
0 0 0 0 0 0
0 0 0 -5 0 3
0 0 0 0 0 0
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 41
Experiment No:9
Aim :Using TCP/IP sockets, write a client – server program to make the client send the file
name and to make the server send back the contents of the requested file if present.
Implement the above program using as message queues or FIFOs as IPC channels
.
Program
File Client
import java.io.*;
import java.net.*;
import java.util.*;
class Clientfile
{ public static void main(String args[])
{
Try
{
BufferedReader in=new BufferedReader(new
InputStreamReader(System.in)); Socket clsct=new Socket("127.0.0.1",139);
DataInputStream din=new DataInputStream(clsct.getInputStream());
DataOutputStream dout=new DataOutputStream(clsct.getOutputStream());
System.out.println("Enter the file name:");
String str=in.readLine();
dout.writeBytes(str+'n');
System.out.println("Enter the new file name:");
String str2=in.readLine();
String str1,ss;
FileWriter f=new
FileWriter(str2); char buffer[];
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 42
while(true)
{ str1=din.readLine();
if(str1.equals("-1")) break;
System.out.println(str1);
buffer=new char[str1.length()];
str1.getChars(0,str1.length(),buffer,0);
f.write(buffer);
}
f.close();
clsct.close();
}
catch (Exception e)
{
System.out.println(e);
}}}
Server
import java.io.*;
import java.net.*;
import java.util.*;
class Serverfile
{ public static void main(String args[])
{
Try
{
ServerSocket obj=new ServerSocket(139);
while(true)
{
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 43
Socket obj1=obj.accept();
DataInputStream din=new DataInputStream(obj1.getInputStream());
DataOutputStream dout=new DataOutputStream(obj1.getOutputStream());
String str=din.readLine();
FileReader f=new FileReader(str);
BufferedReader b=new BufferedReader(f);
String s;
while((s=b.readLine())!=null) {
System.out.println(s);
dout.writeBytes(s+'n');
}
f.close();
dout.writeBytes("-1n");
} }
catch(Exception e)
{ System.out.println(e);}
}
}
Output
File content
Computer networks
jhfcgsauf
jbsdava
jbvuesagv
client
Enter the file name:
sample.txt
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 44
server
Computer networks
jhfcgsauf
jbsdava
jbvuesagv
client
Enter the new file name:
net.txt
Computer networks
jhfcgsauf
jbsdava
jbvuesagv
Destination file
Computer networks
jhfcgsauf
jbsdava
jbvuesagv
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 45
Experiment No:10
Aim: Write a program on datagram socket for client/server to display the messages on client
side, typed at the server side.
Program
UDPserver.java
import java.io.*;
import java.net.*;
class UDPserver
{
public static DatagramSocket ds;
public static byte buffer[]=new byte[1024];
public static int clientport=789,serverport=790;
public static void main(String args[])throws Exception
{
ds=new DatagramSocket(clientport);
System.out.println("press ctrl+c to quit the program");
BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
InetAddress ia=InetAddress.geyLocalHost();
while(true)
{
DatagramPacket p=new DatagramPacket(buffer,buffer.length);
ds.receive(p);
String psx=new String(p.getData(),0,p.getLength());
System.out.println("Client:" + psx);
System.out.println("Server:");
String str=dis.readLine();
if(str.equals("end"))
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 46
break;
buffer=str.getBytes();
ds.send(new
DatagramPacket(buffer,str.length(),ia,serverport));
}
}
}
UDPclient.java
import java .io.*;
import java.net.*;
class UDPclient
{
public static DatagramSocket ds;
public static int clientport=789,serverport=790;
public static void main(String args[])throws Exception
{
byte buffer[]=new byte[1024];
ds=new DatagramSocket(serverport);
BufferedReader dis=new BufferedReader(new InputStreamReader(System.in));
System.out.println("server waiting");
InetAddress ia=InetAddress.getLocalHost();
while(true)
{
System.out.println("Client:");
String str=dis.readLine();
if(str.equals("end"))
break;
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 47
buffer=str.getBytes();
ds.send(new DatagramPacket(buffer,str.length(),ia,clientport));
DatagramPacket p=new DatagramPacket(buffer,buffer.length);
ds.receive(p);
String psx=new String(p.getData(),0,p.getLength());
System.out.println("Server:" + psx);
}
}
}
OUTPUT
Server
C:Program FilesJavajdk1.5.0bin>javac UDPserver.java
C:Program FilesJavajdk1.5.0bin>java UDPserver
press ctrl+c to quit the program
Client:Hai Server
Server:
Hello Client
Client:How are You
Server:
I am Fine
Client
C:Program FilesJavajdk1.5.0bin>javac UDPclient.java
C:Program FilesJavajdk1.5.0bin>java UDPclient
server waiting
Client:
Hai Server
Server:Hello Clie
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 48
Client:
How are You
Server:I am Fine
Client:
End
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 49
11. Write a program for simple RSA algorithm to encrypt and decrypt the data.
Before we can start writing the code for RSA algorithm using the programming languages
like C and JAVA, lets first understand what the algorithm is...
Basically RSA is cryprograpic algorithm which is meant to encrypt the data, generally used in
network security applications while we are sending the data from one source to
destination. ..The concept of RSA algorithm starts with a two key concepts, it uses two
keys(asymmetric keys) one is considered as the public key and another is a private key...
It was developed because using the symmetric encryption algorithm is easy but the key
distribution is difficult, so the concept of two key concept appears to be more efficient... The
whole algorithm depends on the fact that "It is not possible to judge the another key when
attack gets one key"
Here in two keys, one key is taken as the public key another as a private key..public key is
available for everyone to access, so whenever sender want to send the data to receiver, he
uses the public key of receiver(as it is available for use to all) and encrypts the data using the
key, this encrypted data is called cipher text. when receiver receives the cipher text, he can
decrypt the data using his private key
Here even if the attacker knows the encryption algorithm, he cant do anything until the keys
are available....This is theoretical part of RSA.. as we know this forum always try to present
implementation details along with description, here am writing the steps used in this
algorithm
Step 1 : Select two prime nos – p & q such as p!=q
Step 2 : Calculate n as product of p & q, i.e. n=pq
Step 3 : Calculate m as product of (p-1) & (q-1) i.e. m = (p-1)(q-1)
Step 4 : Select any integer e<m such that it is co-prime to m, co-prime means gcd(e,m) =1
Step 5 : Calculate d such that de mod m = 1 , i.e. d = e^-1 mod m
Step 6: The public key is {e,n)
The private key is {d,n}
So these are the keys, now if you want to preform some encryption operation using these keys
here are the steps, if you have a text P..its encrypted version(cipher text C is)
C = P^e mod n
To decrpty it back to plain text use
P = C^d mod n
Example:-
1. Select two prime nos – p=7 & q = 17
2. Calculate n as product of p & q, n= 7 X 17=119
3. Calculate m as product of (p-1) & (q-1) , m= 6 X 16 = 96
4. Select any integer e<m such that it is relatively co-prime to m, which in this case, e = 5
5. Calculate d such that de mod m = 1 , i.e. d X e = 1 mod 96 and d < 96
Here ,d=77 as 77 X 5 = 385 = 4 x 96 + 1
6. The public key is { 5,119} and private key is{ 77,119}
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 50
7. Taking plaintext as P=19 and using the public key we get the ciphertext as C=66.
8. Similarly, we use decryption and get the same plaintext using RSA algorithm.
1. Import java.math.BigInteger;
Import java.security.*;
Import java.security.spec.*;
Import java.io.*;
Import javax.crypto.Cipher;
Public class RSA
{
Public staticvoid main(String args[])
{
String srci="";
try{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Please enter any string you want to encrypt");
srci=br.readLine();
}
catch(IOException ioe)
{
System.out.println(ioe.getMessage());
}
try{
KeyPairGenerator kpg=KeyPairGenerator.getInstance("RSA");
kpg.initialize(512);//initialize key pairs to 512 bits ,you can also take 1024 or
2048 bits
KeyPair kp=kpg.genKeyPair();
PublicKey publi=kp.getPublic();
Cipher cipher =Cipher.getInstance("RSA");
cipher.init(Cipher.ENCRYPT_MODE,publi);
byte[]src=srci.getBytes();//converting source data into byte array
byte[] cipherData = cipher.doFinal(src);//use this method to finally encrypt
data
String srco=new String(cipherData);//converting byte array into string
System.out.println();
System.out.println("Encrypted data is:-"+srco);
PrivateKey privatei=kp.getPrivate();//Generating private key
Cipher cipheri=Cipher.getInstance("RSA");//Intializing 2nd instance of Cipher
class
cipheri.init(Cipher.DECRYPT_MODE, privatei);//Setting to decrypt_mode
byte[] cipherDat = cipheri.doFinal(cipherData);//Finally decrypting data
String decryptdata=new String(cipherDat);
System.out.println("Decrypted data:-"+decryptdata);
}
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET, Mukka Page 51
catch(Exception e)
{
System.out.println(e.getMessage());
}
}
} package com.sanfoundry.setandstring;
2.
3. import java.io.DataInputStream;
4. import java.io.IOException;
5. import java.math.BigInteger;
6. import java.util.Random;
7.
8. public class RSA
9. {
10. private BigInteger p;
11. private BigInteger q;
12. private BigInteger N;
13. private BigInteger phi;
14. private BigInteger e;
15. private BigInteger d;
16. private int bitlength = 1024;
17. private Random r;
18.
19. public RSA()
20. {
21. r = new Random();
22. p = BigInteger.probablePrime(bitlength, r);
23. q = BigInteger.probablePrime(bitlength, r);
24. N = p.multiply(q);
25. phi =
p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
26. e = BigInteger.probablePrime(bitlength / 2, r);
27. while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 &&
e.compareTo(phi) < 0)
28. {
29. e.add(BigInteger.ONE);
30. }
31. d = e.modInverse(phi);
32. }
33.
34. public RSA(BigInteger e, BigInteger d, BigInteger N)
35. {
36. this.e = e;
37. this.d = d;
38. this.N = N;
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET, Mukka Page 52
39. }
40.
41. @SuppressWarnings("deprecation")
42. public static void main(String[] args) throws IOException
43. {
44. RSA rsa = new RSA();
45. DataInputStream in = new DataInputStream(System.in);
46. String teststring;
47. System.out.println("Enter the plain text:");
48. teststring = in.readLine();
49. System.out.println("Encrypting String: " + teststring);
50. System.out.println("String in Bytes: "
51. + bytesToString(teststring.getBytes()));
52. // encrypt
53. byte[] encrypted = rsa.encrypt(teststring.getBytes());
54. // decrypt
55. byte[] decrypted = rsa.decrypt(encrypted);
56. System.out.println("Decrypting Bytes: " +
57.
bytesToString(decrypted));
System.out.println("Decrypted String: " + new
58.
String(decrypted));
}
59.
60. private static String bytesToString(byte[] encrypted)
61. {
62. String test = "";
63. for (byte b : encrypted)
64. {
65. test += Byte.toString(b);
66. }
67. return test;
68. }
69.
70. // Encrypt message
71. public byte[] encrypt(byte[] message)
72. {
73. return (new BigInteger(message)).modPow(e,
N).toByteArray();
74. }
75.
76. // Decrypt message
77. public byte[] decrypt(byte[] message)
78. {
79. return (new
N).toByteArray();
BigInteger(message)).modPow(d,
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET, Mukka Page 53
80.
81.
}
}
$ javac RSA.java
$ java RSA
Enter the plain text:
Sanfoundry
Encrypting String: Sanfoundry
String in Bytes: 8397110102111117110100114121
Decrypting Bytes: 8397110102111117110100114121
Decrypted String: Sanfoundry
Output:
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 54
12. Write a program for congestion control using leaky bucket algorithm.
Aim: TO IMPLEMENT LEAKY BUCKET ALGORITHM IN JAVA
filename:Licky.java
*/
import java.io.*; import
java.util.*;
class Queue
{
int q[],f=0,r=0,size;void
insert(int n)
{
Scanner in = new Scanner(System.in);q=new int[10];
for(int i=0;i<n;i++)
{
System.out.print("nEnter " + i + " element: ");int ele=in.nextInt();
if(r+1>10)
{
System.out.println("nQueue is full nLost Packet: "+ele);break;
}
else
{ r++;
q[i]=ele;
}
}
}
void delete()
{
Scanner in = new Scanner(System.in);Thread t=new
Thread();
if(r==0)
System.out.print("nQueue empty ");
{
{
try
{
}
else
for(int i=f;i<r;i++)
t.sleep(1000);
catch(Exception e){} System.out.print("nLeaked Packet:
"+q[i]);f++;
}
}
System.out.println();
}
}
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 55
class Licky extends Thread
{
public static void main(String ar[])throws Exception
{
Queue q=new Queue();
Scanner src=new Scanner(System.in); System.out.println("nEnter the packets to
be sent:");int size=src.nextInt();
q.insert(size);
q.delete();
}
}
OUTPUT
bash-3.00$ javac Licky.javabash-3.00$
java Licky
Enter the packets to be sent:11
Enter 0 element: 1
Enter 1 element: 0
Enter 2 element: 2
Enter 3 element: 3
Enter 4 element: 4
Enter 5 element: 5
Enter 6 element: 6
Enter 7 element: 7
Enter 8 element: 8
Enter 9 element: 9
Enter 10 element: 10
Queue is full Lost
Packet: 10
Leaked Packet: 1
Leaked Packet: 0
Leaked Packet: 2
Leaked Packet: 3
Leaked Packet: 4
Leaked Packet: 5
Leaked Packet: 6
Leaked Packet: 7
Leaked Packet: 8
Leaked Packet: 9
Computer Networks Lab (19CSL56)
Dept of C.S & E. SUCET,Mukka Page 56
1. What is socket? How it is implemented?
2. What are the different system calls on client side and server side implementation?
3. How to convert single client into multiple clients handling in server?
4. What are the differences between SOCK_STREAM, SOCK_DGRAM, and
SOCK_RAM?What is their level of implementation?
5. Explain need of sock adder_ in structure and IN ADDR_ANY.
6. What is FIFO? How to implement Multiple FIFOs. Disadvantages of FIFO?
7. Which are the different IPC Primitives? Explain Why IPC Primitives are required?
8. Explain the purpose of RS algorithm? What is Public and Private Key? How to
find publicand private key in RSA algorithm?
9. List some Cryptographic algorithms?
10. What is congestion? Explain leaky bucket and token bucket algorithm?
What are itsdisadvantages of each?
11. List other congestion control algorithm.
12. What are the disadvantages of RSA Algorithm?
13. What is the need for routing protocols? List some routing protocols. Which are
commonrouting algorithms used by routing protocols
14. Disadvantages of Distance vector routing. Explain the method to
overcome suchdisadvantage.
15. What is CRC? What is the need for CRC? Which Layer it is implemented?
16. Can CRC be employed for error correction if so how.
17. Explain steps of error correction and error detection. What is encoding and decoding,
why it isrequired?
18. What is Hamming code? Can it be used for error detection and correction how?
19. What are linear block codes? Explain their advantages.
20. What is protocol? List some protocols. How to modify existing protocol?
21. Difference between TCP/IP and OSI Layer Model?
22. Difference between Router, Bridge, Gateway channel. In which layer it is used?
23. Difference between hub and switch. Which is more compatible and reliable?
24. Explain various Ethernet standards.
25. Difference between IP and MAC address.
26. In which layer ATM protocol is used? Explain the purpose.
27. In Which layer or protocol which converts IP to MAC Address.
28. Which are the different collision detection protocols?
29. Which are the different channelization protocol and explain their needs?
30. Explain term error rate, bandwidth, throughput transmission delay, BER,
Interarrival time.What is unit of bandwidth?
31. What is congestion/contention Window? How it is constructed and managed and
by whichlayer?
32. What is ping utility? How it is implemented?
33. Which are different parameters in ICMP protocol? Explain purpose of ICMP.
34. List and explain different link types. Differentiate its characteristics.
35. List TCP and UDP Properties?
36. Why TCP is more reliable than UDP?
37. Is data rate and bandwidth are same?
38. Difference between ESS and BSS. Explain various elements composing the structure of
BSS.
39. Explain various factors that results in congestion and collision.
40. Explain QOS and different measures taken for implementing QOS in network.
41. List different N/W topologies.
42. Difference between Data rate versus Throughput.
43. List the meaning and term used for data in different layers of TCP/IP protocol suite.
VIVA QUESTIONS

Más contenido relacionado

La actualidad más candente

Phasor data concentrator or i pdc
Phasor data concentrator or i pdcPhasor data concentrator or i pdc
Phasor data concentrator or i pdc
Nitesh Pandit
 
Cache performance-x86-2009
Cache performance-x86-2009Cache performance-x86-2009
Cache performance-x86-2009
Léia de Sousa
 
Wide area frequency easurement system iitb
Wide area frequency easurement system iitbWide area frequency easurement system iitb
Wide area frequency easurement system iitb
PanditNitesh
 
An octa core processor with shared memory and message-passing
An octa core processor with shared memory and message-passingAn octa core processor with shared memory and message-passing
An octa core processor with shared memory and message-passing
eSAT Journals
 
Operating System-Threads-Galvin
Operating System-Threads-GalvinOperating System-Threads-Galvin
Operating System-Threads-Galvin
Sonali Chauhan
 

La actualidad más candente (20)

43
4343
43
 
Co question 2008
Co question 2008Co question 2008
Co question 2008
 
shashank_hpca1995_00386533
shashank_hpca1995_00386533shashank_hpca1995_00386533
shashank_hpca1995_00386533
 
Phasor data concentrator or i pdc
Phasor data concentrator or i pdcPhasor data concentrator or i pdc
Phasor data concentrator or i pdc
 
Introduction to Parallel Distributed Computer Systems
Introduction to Parallel Distributed Computer SystemsIntroduction to Parallel Distributed Computer Systems
Introduction to Parallel Distributed Computer Systems
 
Cache performance-x86-2009
Cache performance-x86-2009Cache performance-x86-2009
Cache performance-x86-2009
 
Load module kernel
Load module kernelLoad module kernel
Load module kernel
 
S peculative multi
S peculative multiS peculative multi
S peculative multi
 
Nanokernel
NanokernelNanokernel
Nanokernel
 
Implementation of RISC-Based Architecture for Low power applications
Implementation of RISC-Based Architecture for Low power applicationsImplementation of RISC-Based Architecture for Low power applications
Implementation of RISC-Based Architecture for Low power applications
 
Wide area frequency easurement system iitb
Wide area frequency easurement system iitbWide area frequency easurement system iitb
Wide area frequency easurement system iitb
 
REPORT_INTERNSHIP
REPORT_INTERNSHIPREPORT_INTERNSHIP
REPORT_INTERNSHIP
 
Operating system
Operating systemOperating system
Operating system
 
Hyper thread technology
Hyper thread technologyHyper thread technology
Hyper thread technology
 
Multi-Core on Chip Architecture *doc - IK
Multi-Core on Chip Architecture *doc - IKMulti-Core on Chip Architecture *doc - IK
Multi-Core on Chip Architecture *doc - IK
 
An octa core processor with shared memory and message-passing
An octa core processor with shared memory and message-passingAn octa core processor with shared memory and message-passing
An octa core processor with shared memory and message-passing
 
Os
OsOs
Os
 
ECML-2015 Presentation
ECML-2015 PresentationECML-2015 Presentation
ECML-2015 Presentation
 
Pipelining
PipeliningPipelining
Pipelining
 
Operating System-Threads-Galvin
Operating System-Threads-GalvinOperating System-Threads-Galvin
Operating System-Threads-Galvin
 

Similar a Cn lab manual sb 19_scsl56 (1)

COA RKGITM #sem education purpose ppt good for student
COA RKGITM #sem education purpose ppt good for studentCOA RKGITM #sem education purpose ppt good for student
COA RKGITM #sem education purpose ppt good for student
mohitmehra75
 

Similar a Cn lab manual sb 19_scsl56 (1) (20)

Ade manual with co po-18scheme
Ade manual with co po-18schemeAde manual with co po-18scheme
Ade manual with co po-18scheme
 
Cs8581 networks lab manual 2017
Cs8581 networks lab manual   2017Cs8581 networks lab manual   2017
Cs8581 networks lab manual 2017
 
Digital System Design with FPGAs Lab Manual.pdf
Digital System Design with FPGAs Lab Manual.pdfDigital System Design with FPGAs Lab Manual.pdf
Digital System Design with FPGAs Lab Manual.pdf
 
IT6511 Networks Laboratory
IT6511 Networks LaboratoryIT6511 Networks Laboratory
IT6511 Networks Laboratory
 
Hdllab1
Hdllab1Hdllab1
Hdllab1
 
Cs8383 oop lab manual-2019
Cs8383 oop lab manual-2019Cs8383 oop lab manual-2019
Cs8383 oop lab manual-2019
 
Dsp lab
Dsp labDsp lab
Dsp lab
 
Dsp lab manual
Dsp lab manualDsp lab manual
Dsp lab manual
 
CS8383 Object Oriented Programming Laboratory Manual
CS8383 Object Oriented Programming Laboratory ManualCS8383 Object Oriented Programming Laboratory Manual
CS8383 Object Oriented Programming Laboratory Manual
 
vtu data structures lab manual bcs304 pdf
vtu data structures lab manual bcs304 pdfvtu data structures lab manual bcs304 pdf
vtu data structures lab manual bcs304 pdf
 
Dsp (1)
Dsp (1)Dsp (1)
Dsp (1)
 
Np lab
Np labNp lab
Np lab
 
AI_LAB_Manual in c with all the programs
AI_LAB_Manual in c with all the programsAI_LAB_Manual in c with all the programs
AI_LAB_Manual in c with all the programs
 
WIRELESS LAN TECHNOLOGIES
WIRELESS LAN TECHNOLOGIESWIRELESS LAN TECHNOLOGIES
WIRELESS LAN TECHNOLOGIES
 
COA RKGITM #sem education purpose ppt good for student
COA RKGITM #sem education purpose ppt good for studentCOA RKGITM #sem education purpose ppt good for student
COA RKGITM #sem education purpose ppt good for student
 
ST4211_NUMERICAL-AND-INITE-ELEMENT-ANALYSIS-LABORATORY.pdf
ST4211_NUMERICAL-AND-INITE-ELEMENT-ANALYSIS-LABORATORY.pdfST4211_NUMERICAL-AND-INITE-ELEMENT-ANALYSIS-LABORATORY.pdf
ST4211_NUMERICAL-AND-INITE-ELEMENT-ANALYSIS-LABORATORY.pdf
 
Fluid-Machinery-1.pdf this document is used for cput lecture in mechanical e...
Fluid-Machinery-1.pdf this document is used for cput  lecture in mechanical e...Fluid-Machinery-1.pdf this document is used for cput  lecture in mechanical e...
Fluid-Machinery-1.pdf this document is used for cput lecture in mechanical e...
 
01.b.e. cse final
01.b.e. cse final01.b.e. cse final
01.b.e. cse final
 
SE LAB MANUAL (R16).pdf
SE LAB MANUAL (R16).pdfSE LAB MANUAL (R16).pdf
SE LAB MANUAL (R16).pdf
 
01.B.E. CSE final.doc
01.B.E. CSE final.doc01.B.E. CSE final.doc
01.B.E. CSE final.doc
 

Último

Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptx
chumtiyababu
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Kandungan 087776558899
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
AldoGarca30
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
mphochane1998
 

Último (20)

Thermal Engineering Unit - I & II . ppt
Thermal Engineering  Unit - I & II . pptThermal Engineering  Unit - I & II . ppt
Thermal Engineering Unit - I & II . ppt
 
AIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech studentsAIRCANVAS[1].pdf mini project for btech students
AIRCANVAS[1].pdf mini project for btech students
 
Verification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptxVerification of thevenin's theorem for BEEE Lab (1).pptx
Verification of thevenin's theorem for BEEE Lab (1).pptx
 
School management system project Report.pdf
School management system project Report.pdfSchool management system project Report.pdf
School management system project Report.pdf
 
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak HamilCara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
Cara Menggugurkan Sperma Yang Masuk Rahim Biyar Tidak Hamil
 
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
1_Introduction + EAM Vocabulary + how to navigate in EAM.pdf
 
Introduction to Serverless with AWS Lambda
Introduction to Serverless with AWS LambdaIntroduction to Serverless with AWS Lambda
Introduction to Serverless with AWS Lambda
 
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKARHAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
HAND TOOLS USED AT ELECTRONICS WORK PRESENTED BY KOUSTAV SARKAR
 
Moment Distribution Method For Btech Civil
Moment Distribution Method For Btech CivilMoment Distribution Method For Btech Civil
Moment Distribution Method For Btech Civil
 
Thermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.pptThermal Engineering -unit - III & IV.ppt
Thermal Engineering -unit - III & IV.ppt
 
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
Bhubaneswar🌹Call Girls Bhubaneswar ❤Komal 9777949614 💟 Full Trusted CALL GIRL...
 
Double Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torqueDouble Revolving field theory-how the rotor develops torque
Double Revolving field theory-how the rotor develops torque
 
Unleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leapUnleashing the Power of the SORA AI lastest leap
Unleashing the Power of the SORA AI lastest leap
 
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments""Lesotho Leaps Forward: A Chronicle of Transformative Developments"
"Lesotho Leaps Forward: A Chronicle of Transformative Developments"
 
Work-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptxWork-Permit-Receiver-in-Saudi-Aramco.pptx
Work-Permit-Receiver-in-Saudi-Aramco.pptx
 
Computer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to ComputersComputer Lecture 01.pptxIntroduction to Computers
Computer Lecture 01.pptxIntroduction to Computers
 
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
Navigating Complexity: The Role of Trusted Partners and VIAS3D in Dassault Sy...
 
DC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equationDC MACHINE-Motoring and generation, Armature circuit equation
DC MACHINE-Motoring and generation, Armature circuit equation
 
Wadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptxWadi Rum luxhotel lodge Analysis case study.pptx
Wadi Rum luxhotel lodge Analysis case study.pptx
 
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best ServiceTamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
Tamil Call Girls Bhayandar WhatsApp +91-9930687706, Best Service
 

Cn lab manual sb 19_scsl56 (1)

  • 1. SRINIVAS UNIVERSITY COLLEGE OF ENGINEERING AND TECHNOLOGY MUKKA – 574146 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING LAB MANUAL ON COMPUTER NETWORKS Subject Code: 19SCSL56 2021-2022 Prepared by, Ms. SHIFANA BEGUM Assistant Professor, Dept of C S & E, SUCET Name Section / Branch Semester USN
  • 2. SRINIVAS UNIVERSITY COLLEGE OF ENGINEERING AND TECHNOLOGY, MUKKA - 574146 DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING Institution Vision To transform society by imparting quality technical education in dynamic equilibrium with social, ecological and economic environment, striving continuously for excellence in education, research and technological service to the nation Institution Mission To provide knowledge based technological education to the students and train them as a competent professional manpower with ethical values to fulfill the needs of the society and industry by implementing the state-of the art education including technological innovation. Vision of Department of Computer Science and Engineering To impart state of the art technical education by providing conductive learning environment for technological innovation, to inculcate research culture and skills necessary to meet the changing needs of the industry and the society in the field of Computer Science and Engineering and allied disciplines. Mission of Department of Computer Science and Engineering To be a centre of excellence in Computer Science and Engineering and to create qualified Computer Science Engineers with a vision to take up the demanding challenges of the industry and society in emerging fields of Computer Science and Engineering Programme Educational Objectives (PEOs) of Department of Computer Science and Engineering 1. To prepare students for successful careers in industry that meet the needs of Indian and multinational companies with latest technical skills 2. To develop the ability among students to synthesize data and technical concepts for application to product innovation, design & development and manufacturing. 3. To provide opportunity for students to work as part of teams on multidisciplinary projects with communication skills 4. To provide students with a sound foundation in the mathematical, scientific and engineering fundamentals necessary to formulate, solve and analyze engineering problems. 5. To promote student awareness on lifelong learning and to introduce them to 7 professional ethics and codes of professional practice.
  • 3. PROGRAM OUTCOMES (POs) Engineering Graduates should possess the following: 1.Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals, and an engineering specialization to the solution of complex engineering problems. 2.Problem analysis: Identify, formulate, review 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 the specified needs with appropriate consideration for the public health and safety, and the cultural, societal, and environmental considerations. 4.Conduct investigations of complex problems: Use research-based knowledge and research methods including design of experiments, analysis and interpretation of data, and synthesis of the 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 understanding of the limitations. 6.The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal, health, safety, legal and cultural issues and the consequent responsibilities relevant to the professional engineering practice. 7.Environment and sustainability: Understand the impact of the professional engineering solutions in societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable development. 8.Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the engineering practice. 9.Individual and team work: Function effectively as an individual, and as a member or leader in diverse teams, and in multidisciplinary settings.
  • 4. 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.Project management and finance: Demonstrate knowledge and understanding of the 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 multi-disciplinary environments. 12.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.
  • 5. GENERAL LABORATORY INSTRUCTIONS: 1. Students are advised to come to the laboratory at least 5 minutes before (to starting time), those who come after 5 minutes will not be allowed into the lab. 2. Plan your task properly much before to the commencement, come prepared to the lab with the program / experiment details. 3. Student should enter into the laboratory with: a. Laboratory observation notes with all the details (Problem statement, Aim, Algorithm, Procedure, Program, Expected Output, etc.,) filled in for the lab session. b. Laboratory Record updated up to the last session experiments and other utensils (if any) needed in the lab. c. Proper Dress code and Identity card. 4. Sign in the laboratory login register, write the TIME-IN, and occupy the computer system allotted to you by the faculty. 5. Execute your task in the laboratory, and record the results / output in the lab observation note book, and get certified by the concerned faculty. 6. All the students should be polite and cooperative with the laboratory staff, must maintain the discipline and decency in the laboratory. 8. Students / Faculty must keep their mobile phones in SILENT mode during the lab sessions. Misuse of the equipment, misbehaviors with the staff and systems etc., will attract severe punishment. 9. Students must take the permission of the faculty in case of any urgency to go out . 10. Students should LOG OFF/ SHUT DOWN the computer system before he/she leaves the lab after completing the task (experiment) in all aspects. He/she must ensure the system / seat is kept properly. Lab Incharge Head of the Department
  • 6. COMPUTER NETWORKS LABORATORY Course Code : 19SCSL56 IA Marks : 50 Hours/Week : 3 Exam Hours : 3 Credits : 2 Exam Marks : 50 Total Hours : 42 Course Objectives:  Demonstrate operation of network and its management commands.  Simulate and demonstrate the performance of GSM and CDMA.  Implement data link layer and transport layer protocols. Course Outcomes: After studying this course, students will be able to: CO1: Analyze and Compare various networking protocols. CO2: Demonstrate the working of different concepts of networking. CO3: Implement, analyze and evaluate networking protocols in NS2 / NS3. Description (If any):  For the experiments below modify the topology and parameters set for the experiment and take multiple rounds of reading and analyze the results available in log files. Plot necessary graphs and conclude. Use NS2/NS3. Lab Experiments: Part A 1. Implement three nodes point – to – point network with duplex links between them. Set the queue size, vary the bandwidth and find the number of packets dropped. 2. Implement transmission of ping messages/trace route over a network topology consisting of 6 nodes and find the number of packets dropped due to congestion. 3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot congestion window for different source / destination. 4. 4. Implement simple ESS and with transmitting nodes in wire-less LAN by simulation and determine the performance with respect to transmission of packets. 5. Implement and study the performance of GSM on NS2/NS3 (Using MAC layer) or equivalent environment. 6. Implement and study the performance of CDMA on NS2/NS3 (Using stack
  • 7. called Call net) or equivalent environment. Part B Implement the following in Java: 1. Write a program for error detecting code using CRC-CCITT (16- bits). 2. Write a program to find the shortest path between vertices using bellman-ford algorithm. 3. Using TCP/IP sockets, write a client – server progr am to make the client send the file name and to make the server send back the contents of the requested file if present. 4. Write a program on datagram socket for client/server to display the messages on client side, typed at the server side. 5. Write a program for simple RSA algorithm to encrypt and decrypt the data. 6. Write a program for congestion control using leaky bucket algorithm. Conduction of Practical Examination:  All laboratory experiments from part A and part B are to be included for practical examination.  Students are allowed to pick one experiment from the lot.  Strictly follow the instructions as printed on the cover page of answer script.  Marks Distribution: Procedure+Conduction+Viva:12+28+10=50 Marks  Change of experiment is allowed only once and marks allotted to the procedure part to be made zero.
  • 8. CONTENTS SL No. Experiments Page No Marks Remarks Introduction to NS2 1-11 1 Implement three nodes point – to – point network with duplex links between them. Set the queue size, vary the bandwidth and find the number of packets dropped. 12-14 2 Implement transmission of ping messages/trace route over a network topology consisting of 6 nodes and find the number of packets dropped due to congestion. 15-19 3 Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot congestion window for different source / destination. 20-23 4 Implement simple ESS and with transmitting nodes in wire-less LAN by simulation and determine the performance with respect to transmission of packets. 24-27 5 Implement and study the performance of GSM on NS2/NS3 (Using MAC layer) or equivalent environment. 28-30 6 Implement and study the performance of CDMA on NS2/NS3 (Using stack called Call net) or equivalent environment 31-34 7 Program for error detecting code using CRC-CCITT (16- bits). 35-36 8 Program to find the shortest path between vertices using bellman-ford algorithm. 37-40 9 Client – server program to make the client send the file name and to make the server send back the contents of the requested file if present. 41-44 10 Program on datagram socket for client/server to display the messages on client side, typed at the server side. 45-48 11 Program for simple RSA algorithm to encrypt and decrypt the data. 49-53 12 Program for congestion control using leaky bucket algorithm. 54-55
  • 9. Computer Networks Lab (19SCSL56) Dept of C.S & E, SUCET ,MUKKA Page 1 Introduction to NS-2:  Widely known as NS2, is simply an event driven simulation tool.  Useful in studying the dynamic nature of communication networks.  Simulation of wired as well as wireless network functions and protocols (e.g., routing algorithms, TCP, UDP) can be done using NS2.  In general, NS2 provides users with a way of specifying such network protocols and simulating their corresponding behaviors. Basic Architecture of NS2 Tcl scripting • Tcl is a general purpose scripting language. [Interpreter] • Tcl runs on most of the platforms such as Unix, Windows, and Mac. • The strength of Tcl is its simplicity. • It is not necessary to declare a data type for variable prior to the usage. Basics of TCL Syntax: command arg1 arg2 arg3  Hello World! puts stdout{Hello, World!} Hello, World!  Variables Command Substitution set a 5 set len [string length foobar] set b $a set len [expr [string length foobar] + 9]
  • 10. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET, Mukka Page 2 Simple Arithmetic expr 7.2 / 4  Procedures proc Diag {a b} { set c [expr sqrt($a * $a + $b * $b)] return $c } puts “Diagonal of a 3, 4 right triangle is [Diag 3 4]” Output: Diagonal of a 3, 4 right triangle is 5.0  Loops while{$i < $n} { for {set i 0} {$i < $n} {incr i} { . . . . . . } } Wired TCL Script Components Create the event scheduler Open new files & turn on the tracing Create the nodes Setup the links Configure the traffic type (e.g., TCP, UDP, etc) Set the time of traffic generation (e.g., CBR, FTP) Terminate the simulation NS Simulator Preliminaries. 1. Initialization and termination aspects of the ns simulator. 2. Definition of network nodes, links, queues and topology. 3. Definition of agents and of applications. 4. The nam visualization tool. 5. Tracing and random variables. Initialization and Termination of TCL Script in NS-2 An ns simulation starts with the command Which is thus the first line in the tcl script? This line declares a new variable as using the set command, you can call this variable as you wish, In general people declares it as ns because it set ns [new Simulator]
  • 11. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET, Mukka Page 3 is an instance of the Simulator class, so an object the code[new Simulator] is indeed the installation of the class Simulator using the reserved word new. In order to have output files with data on the simulation (trace files) or files used for visualization (nam files), we need to create the files using “open” command: #Open the Trace file #Open the NAM trace file The above creates a dta trace file called “out.tr” and a nam visualization trace file called “out.nam”.Within the tcl script,these files are not called explicitly by their names,but instead by pointers that are declared above and called “tracefile1” and “namfile” respectively.Remark that they begins with a # symbol.The second line open the file “out.tr” to be used for writing,declared with the letter “w”.The third line uses a simulator method called trace-all that have as parameter the name of the file where the traces will go. The last line tells the simulator to record all simulation traces in NAM input format.It also gives the file name that the trace will be written to later by the command $ns flush- trace.In our case,this will be the file pointed at by the pointer “$namfile”,i.e the file “out.tr”. The termination of the program is done using a “finish” procedure. #Define a „finish‟ procedure Proc finish { } { global ns tracefile1 namfile $ns flush-trace Close $tracefile1 Close $namfile Exec nam out.nam & Exit 0 } set tracefile1 [open out.tr w] $ns trace-all $tracefile1 set namfile [open out.nam w] $ns namtrace-all $namfile
  • 12. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET, Mukka Page 4 $ns duplex-link $n0 $n2 10Mb 10ms DropTail $ns at 125.0 “finish” 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, will be used to call “finish” at time 125sec.Indeed,the at method of the simulator allows us to schedule events explicitly. The simulation can then begin using the command Definition of a network of links and nodes The way to define a node is 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: Which means that $n0 and $n2 are connected using a bi-directional link that has 10ms of propagation delay and a capacity of 10Mb per sec for each direction. To define a directional link instead of a bi-directional one, we should replace “duplex- link” by “simplex-link”. In NS, an output queue of a node is implemented as a part of each link whose input is that node. The definition of the link then includes the way to handle overflow at that queue. In our case, if the buffer capacity of the output queue is exceeded then the last packet to $ns run set n0 [$ns node]
  • 13. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET, Mukka Page 5 set sink [new Agent /TCPSink] #set Queue Size of link (n0-n2) to 20 $ns queue-limit $n0 $n2 20 arrive is dropped. Many alternative options exist, such as the RED (Random Early Discard) mechanism, the FQ (Fair Queuing), the DRR (Deficit Round Robin), the stochastic Fair Queuing (SFQ) and the CBQ (which including a priority and a round-robin scheduler). Dept of ISE, CIT, Gubbi 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: Agents and Applications We need to define routing (sources, destinations) the agents (protocols) the application that use them. FTP over TCP TCP is a dynamic reliable congestion control protocol. It uses Acknowledgements created by the destination to know whether packets are well received. There are number variants of the TCP protocol, such as Tahoe, Reno, NewReno, Vegas. The type of agent appears in the first line: The command $ns attach-agent $n0 $tcp defines the source node of the tcp connection. The command Defines the behavior of the destination node of TCP and assigns to it a pointer called sink. set tcp [new Agent/TCP]
  • 14. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET, Mukka Page 6 #Setup a UDP connection #setup a CBR over UDP connection The below shows the definition of a CBR application using a UDP agent The command $ns attach-agent $n4 $sink defines the destination node. The command $ns connect $tcp $sink finally makes the TCP connection between the source and destination nodes. 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. set udp [new Agent/UDP] $ns attach-agent $n1 $udp set null [new Agent/Null] $ns attach-agent $n5 $null $ns connect $udp $null $udp set fid_2 set cbr [new Application/Traffic/CBR] $cbr attach-agent $udp $cbr set packetsize_ 100 $cbr set rate_ 0.01Mb $cbr set random_ false
  • 15. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET, Mukka Page 7 CBR over UDP A UDP source and destination is defined in a similar way as in the case of TCP. Instead of defining the rate in the command $cbr set rate_ 0.01Mb, one can define the time interval between transmission of packets using the command. The packet size can be set to some value using 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: 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 Structure of Trace Files When tracing into an output ASCII file, the trace is organized in 12 fields as follows in fig shown below, The meaning of the fields are: Event Time From Node To Node PKT Type PKT Size Flags Fid Src Addr Dest Addr Seq Num Pkt id $cbr set interval_ 0.005 $cbr set packetSize_ <packet size> $ns at <time> <event> $ns at 0.1 “$cbr start” $ns at 1.0 “ $ftp start” $ns at 124.0 “$ftp stop” $ns at 124.5 “$cbr stop”
  • 16. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET, Mukka Page 8 1. The first field is the event type. It is given by one of four possible symbols r, +, -, d which correspond respectively to receive (at the output of the link), enqueued, dequeued and dropped. 2. The second field gives the time at which the event occurs. 3. Gives the input node of the link at which the event occurs. 4. Gives the output node of the link at which the event occurs. 5. Gives the packet type (eg CBR or TCP) 6. Gives the packet size 7. Some flags 8. This is the flow id (fid) of IPv6 that a user can set for each flow at the input OTcl script one can further use this field for analysis purposes; it is also used when specifying stream color for the NAM display. 9. This is the source address given in the form of “node.port”. 10. This is the destination address, given in the same form. 11. This is the network layer protocol’s packet sequence number. Even though UDP implementations in a real network do not use sequence number, ns keeps track of UDP packet sequence number for analysis purposes 12. The last field shows the Unique id of the packet. 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: Options are listed here /-bd <color> (Border) This specifies the border color of the xgraph window. /-bg <color> (Background) This specifies the background color of the xgraph window. Xgraph [options] file-name
  • 17. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET, Mukka Page 9 /-fg<color> (Foreground) This specifies the foreground color of the xgraph window. /-lf <fontname> (LabelFont) All axis labels and grid labels are drawn using this font. /-t<string> (Title Text) This string is centered at the top of the graph. /-x <unit name> (XunitText) This is the unit name for the x-axis. Its default is “X”. /-y <unit name> (YunitText) This is the unit name for the y-axis. Its default is “Y”. Awk- An Advanced awk is a programmable, pattern-matching, and processing tool available in UNIX. It works equally well with text and numbers. awk is not just a command, but a programming language too. In other words, awk utility is a pattern scanning and processing language. It searches one or more files to see if they contain lines that match specified patterns and then perform associated actions, such as writing the line to the standard output or incrementing a counter each time it finds a match. Syntax: 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 awk option ‘selection_criteria {action}’ file(s)
  • 18. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET, Mukka Page 10 printf “ %3f %20s %-12s %dn”, kount,$2,$3,$6 }‟ empn.lst THE –f OPTION: STORING awk PROGRAMS IN A FILE You should holds large awk programs in separate file and provide them with the awk extension for easier identification. Let’s first store the previous program in the file empawk.awk: $ cat empawk.awk Observe that this time we haven’t used quotes to enclose the awk program. You can now use awk with the –f filename option to obtain the same output: THE BEGIN AND END SECTIONS Awk statements are usually applied to all lines selected by the address, and if there are no addresses, then they are applied to every line of input. But, if you have to print something before processing the first line, for example, a heading, then the BEGIN section can be used gainfully. Similarly, the end section useful in printing some totals after processing is over. The BEGIN and END sections are optional and take the form BEGIN {action} END {action} These two sections, when present, are delimited by the body of the awk program. You can use them to print a suitable heading at the beginning and the average salary at the end. BUILT-IN VARIABLES Awk has several built-in variables. They are all assigned automatically, though it is also possible for a user to reassign some of them. You have already used NR, which signifies the record number of the current line. We’ll now have a brief look at some of the other variable. The FS Variable: as stated elsewhere, awk uses a contiguous string of spaces as the default field delimiter. FS redefines this field separator, which in the sample database happens to be the |. When used at all, it must occur in the BEGIN section so that the body of the program knows its value before it starts processing: BEGIN {FS=”|”} This is an alternative to the –F option which does the same thing. Awk –F”|” –f empawk.awk empn.lst
  • 19. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 11 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
  • 20. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 12 Part-A Experiment No: 1 Aim: Simulate a three node point to point network with duplex links between them. Set queue size and vary the bandwidth and find number of packets dropped. Program: set ns [new Simulator] # Letter S is capital set nf [open PA1.nam w] # open a nam trace file in write mode $ns namtrace-all $nf # nf nam filename set tf [open PA1.tr w] # tf trace filename $ns trace-all $tf proc finish { } { global ns nf tf $ns flush-trace # clears trace file contents close $nf close $tf exec nam PA1.nam & exit 0 } set n0 [$ns node] # creates 3 nodes set n2 [$ns node] set n3 [$ns node] $ns duplex-link $n0 $n2 200Mb 10ms DropTail # establishing links $ns duplex-link $n2 $n3 1Mb 1000ms DropTail $ns queue-limit $n0 $n2 10 set udp0 [new Agent/UDP] # attaching transport layer protocols $ns attach-agent $n0 $udp0 set cbr0 [new Application/Traffic/CBR] # attaching application layer protocols $cbr0 set packetSize_ 500 $cbr0 set interval_ 0.005 $cbr0 attach-agent $udp0 set null0 [new Agent/Null] # creating sink(destination) node $ns attach-agent $n3 $null0 $ns connect $udp0 $null0 $ns at 0.1 "$cbr0 start" $ns at 1.0 "finish" $ns run
  • 21. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 13 AWK file: (Open a new editor using “vi command” and write awk file and save with “.awk” extension) #immediately after BEGIN should open braces „{„ BEGIN{ c=0;} { if($1= ="d") { c++; printf("%st%sn",$5,$11); } } END{ printf("The number of packets dropped =%dn",c); } Steps for execution:  Open vi editor and type program. Program name should have the extension “ .tcl ” [root@localhost ~]# vi lab1.tcl  Save the program by pressing “ESC key” first, followed by “Shift and :” keys simultaneously and type “wq” and press Enter key.  Open vi editor and type awk program. Program name should have the extension “.awk ” [root@localhost ~]# vi lab1.awk  Save the program by pressing “ESC key” first, followed by “Shift and :” keys simultaneously and type “wq” and press Enter key.  Run the simulation program [root@localhost~]# ns lab1.tcl  Here “ns” indicates network simulator. We get the topology shown in the snapshot.  Now press the play button in the simulation window and the simulation will begins.  After simulation is completed run awk file to see the output , [root@localhost~]# awk –f lab1.awk lab1.tr  To see the trace file contents open the file as , [root@localhost~]# vi lab1.tr 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
  • 22. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 14 Contents of Trace File Topology Output
  • 23. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 15 Experiment No:2 Aim: Implement transmission of ping messages/trace route over a network topology consisting of 6 nodes and find the number of packets dropped due to congestion. Program: set ns [ new Simulator ] 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 $ns queue-limit $n0 $n4 5 $ns queue-limit $n2 $n4 3 $ns queue-limit $n4 $n5 2 Agent/Ping instproc recv {from rtt} {
  • 24. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 16 $self instvar node_ puts "node [$nod e_ 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" $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"
  • 25. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 17 $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 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 =%dn",$5,drop); }
  • 26. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 18 Steps for execution 1) Open vi editor and type program. Program name should have the extension “ .tcl ” [root@localhost ~]# vi lab4.tcl 2) Save the program by pressing “ESC key” first, followed by “Shift and :” keys simultaneously and type “wq” and press Enter key. 3) Open vi editor and type awk program. Program name should have the extension “.awk ” [root@localhost ~]# vi lab4.awk 4) Save the program by pressing “ESC key” first, followed by “Shift and :” keys simultaneously and type “wq” and press Enter key. 5) Run the simulation program [root@localhost~]# ns lab4.tcl i) Here “ns” indicates network simulator. We get the topology shown in the snapshot. ii) Now press the play button in the simulation window and the simulation will begins. 6) After simulation is completed run awk file to see the output , [root@localhost~]# awk –f lab4.awk lab4.tr 7) To see the trace file contents open the file as , [root@localhost~]# vi lab4.tr
  • 27. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 19 Topology Output
  • 28. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 20 Experiment No:3 Aim: Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot congestion window for different source / destination. Program: set ns [new Simulator] set tf [open pgm7.tr w] $ns trace-all $tf set nf [open pgm7.nam w] $ns namtrace-all $nf set n0 [$ns node] $n0 color "magenta" $n0 label "src1" set n1 [$ns node] set n2 [$ns node] $n2 color "magenta" $n2 label "src2" set n3 [$ns node] $n3 color "blue" $n3 label "dest2" set n4 [$ns node] set n5 [$ns node] $n5 color "blue" $n5 label "dest1" $ns make-lan "$n0 $n1 $n2 $n3 $n4" 100Mb 100ms LL Queue/ DropTail Mac/802_3 # should come in single line $ns duplex-link $n4 $n5 1Mb 1ms DropTail set tcp0 [new Agent/TCP] $ns attach-agent $n0 $tcp0 set ftp0 [new Application/FTP] $ftp0 attach-agent $tcp0 $ftp0 set packetSize_ 500 $ftp0 set interval_ 0.0001 set sink5 [new Agent/TCPSink] $ns attach-agent $n5 $sink5 $ns connect $tcp0 $sink5 set tcp2 [new Agent/TCP] $ns attach-agent $n2 $tcp2 set ftp2 [new Application/FTP] $ftp2 attach-agent $tcp2 $ftp2 set packetSize_ 600 $ftp2 set interval_ 0.001
  • 29. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 21 set sink3 [new Agent/TCPSink] $ns attach-agent $n3 $sink3 $ns connect $tcp2 $sink3 set file1 [open file1.tr w] $tcp0 attach $file1 set file2 [open file2.tr w] $tcp2 attach $file2 $tcp0 trace cwnd_ # must put underscore ( _ ) after cwnd and no space between them $tcp2 trace cwnd_ proc finish { } { global ns nf tf $ns flush-trace close $tf close $nf exec nam pgm7.nam & exit 0 } $ns at 0.1 "$ftp0 start" $ns at 5 "$ftp0 stop" $ns at 7 "$ftp0 start" $ns at 0.2 "$ftp2 start" $ns at 8 "$ftp2 stop" $ns at 14 "$ftp0 stop" $ns at 10 "$ftp2 start" $ns at 15 "$ftp2 stop" $ns at 16 "finish" $ns run AWK file: (Open a new editor using “vi command” and write awk file and save with “.awk” extension) cwnd:- means congestion window BEGIN { } { if($6= ="cwnd_") # don‟t leave space after writing cwnd_ printf("%ft%ftn",$1,$7); # you must put n in printf } END { }
  • 30. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 22 Steps for execution: 1) Open vi editor and type program. Program name should have the extension “ .tcl ” [root@localhost ~]# vi lab7.tcl 2) Save the program by pressing “ESC key” first, followed by “Shift and :” keys simultaneously and type “wq” and press Enter key. 3) Open vi editor and type awk program. Program name should have the extension “.awk ” [root@localhost ~]# vi lab7.awk 4) Save the program by pressing “ESC key” first, followed by “Shift and :” keys simultaneously and type “wq” and press Enter key. 5) Run the simulation program [root@localhost~]# ns lab7.tcl 6) After simulation is completed run awk file to see the output , i. [root@localhost~]# awk –f lab7.awk file1.tr > a1 ii. [root@localhost~]# awk –f lab7.awk file2.tr > a2 iii. [root@localhost~]# xgraph a1 a2 7) Here we are using the congestion window trace files i.e. file1.tr and file2.tr and we are redirecting the contents of those files to new files say a1 and a2 using output redirection operator (>). 8) To see the trace file contents open the file as , [root@localhost~]# vi lab7.tr
  • 31. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 23 Output Graph
  • 32. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 24 Experiment No:4 Aim: Implement simple ESS and with transmitting nodes in wire-less LAN by simulation and determine the performance with respect to transmission of packets. Program: set ns [new Simulator] set tf [open lab8.tr w] $ns trace-all $tf set topo [new Topography] $topo load_flatgrid 1000 1000 set nf [open lab8.nam w] $ns namtrace-all-wireless $nf 1000 1000 $ns node-config -adhocRouting DSDV -llType LL -macType Mac/802_11 -ifqType Queue/DropTail -ifqLen 50 -phyType Phy/WirelessPhy -channelType Channel/WirelessChannel -prrootype Propagation/TwoRayGround -antType Antenna/OmniAntenna -topoInstance $topo -agentTrace ON -routerTrace ON create-god 3 set n0 [$ns node] set n1 [$ns node] set n2 [$ns node] $n0 label "tcp0" $n1 label "sink1/tcp1" $n2 label "sink2" $n0 set X_ 50 $n0 set Y_ 50 $n0 set Z_ 0 $n1 set X_ 100 $n1 set Y_ 100 $n1 set Z_ 0 $n2 set X_ 600 $n2 set Y_ 600 $n2 set Z_ 0 $ns at 0.1 "$n0 setdest 50 50 15"
  • 33. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 25 $ns at 0.1 "$n1 setdest 100 100 25" $ns at 0.1 "$n2 setdest 600 600 25" set tcp0 [new Agent/TCP] $ns attach-agent $n0 $tcp0 set ftp0 [new Application/FTP] $ftp0 attach-agent $tcp0 set sink1 [new Agent/TCPSink] $ns attach-agent $n1 $sink1 $ns connect $tcp0 $sink1 set tcp1 [new Agent/TCP] $ns attach-agent $n1 $tcp1 set ftp1 [new Application/FTP] $ftp1 attach-agent $tcp1 set sink2 [new Agent/TCPSink] $ns attach-agent $n2 $sink2 $ns connect $tcp1 $sink2 $ns at 5 "$ftp0 start" $ns at 5 "$ftp1 start" $ns at 100 "$n1 setdest 550 550 15" $ns at 190 "$n1 setdest 70 70 15" proc finish { } { global ns nf tf $ns flush-trace exec nam lab8.nam & close $tf exit 0 } $ns at 250 "finish" $ns run AWK file: (Open a new editor using “vi command” and write awk file and save with “.awk” extension) BEGIN{ count1=0 count2=0 pack1=0 pack2=0 time1=0 time2=0 } { if($1= ="r"&& $3= ="_1_" && $4= ="AGT") { count1++ pack1=pack1+$8 time1=$2 } if($1= ="r" && $3= ="_2_" && $4= ="AGT") { count2++ pack2=pack2+$8 time2=$2 } }
  • 34. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 26 END{ printf("The Throughput from n0 to n1: %f Mbps n”, ((count1*pack1*8)/(time1*1000000))); printf("The Throughput from n1 to n2: %f Mbps", ((count2*pack2*8)/(time2*1000000))); } Steps for execution Open vi editor and type program. Program name should have the extension “ .tcl ” [root@localhost ~]# vi lab8.tcl Save the program by pressing “ESC key” first, followed by “Shift and :” keys simultaneously and type “wq” and press Enter key. Open vi editor and type awk program. Program name should have the extension “.awk ” [root@localhost ~]# vi lab8.awk Save the program by pressing “ESC key” first, followed by “Shift and :” keys simultaneously and type “wq” and press Enter key. Run the simulation program [root@localhost~]# ns lab8.tcl o Here “ns” indicates network simulator. We get the topology shown in the snapshot. o Now press the play button in the simulation window and the simulation will begins. After simulation is completed run awk file to see the output , [root@localhost~]# awk –f lab8.awk lab8.tr To see the trace file contents open the file as , [root@localhost~]# vi lab8.tr Topology: Node 1 and 2 are communicating Node 2 is moving towards node 3
  • 35. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 27 Node 2 is coming back from node 3 towards node1 Trace File
  • 36. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 28 Experiment No:5 Aim: Implement and study the performance of GSM on NS2/NS3 (Using MAC layer) or equivalent environment. Source Code: # General Parameters set stop 100 ;# Stop time. # Topology set type gsm ;#type of link: # AQM parameters set minth 30 ; set maxth 0 ; set adaptive 1 ;# 1 for Adaptive RED, 0 for plain RED # Traffic generation. set flows 0 ;# number of long-lived TCP flows set window 30 ;# window for long-lived traffic set web 2 ;# number of web sessions # Plotting statics. set opt(wrap) 100 ;# wrap plots? set opt(srcTrace) is ;# where to plot traffic set opt(dstTrace) bs2;# where to plot traffic #default downlink bandwidth in bps set bwDL(gsm) 9600 #default uplink bandwidth in bps set bwUL(gsm) 9600 #default downlink propagation delay in seconds set propDL(gsm) .500 #default uplink propagation delay in seconds set propUL(gsm) .500 set ns [new Simulator] set tf [open out.tr w] $ns trace-all $t set nodes(is) [$ns node] set nodes(ms) [$ns node] set nodes(bs1) [$ns node] set nodes(bs2) [$ns node] set nodes(lp) [$ns node] proc cell_topo {} { global ns nodes $ns duplex-link $nodes(lp) $nodes(bs1) 3Mbps 10nodes(ms) DropTail $ns duplex-link $nodes(bs1) $nodes(ms) 1 1 RED $ns duplex-link $nodes(ms) $nodes(bs2) 1 1 RED $ns duplex-link $nodes(bs2) $nodes(is) 3Mbps 50nodes(ms) DropTail puts " GSM Cell Topology" } proc set_link_para {t} { global ns nodes bwUL bwDL propUL propDL buf $ns bandwidth $nodes(bs1) $nodes(ms) $bwDL($t) duplex $ns bandwidth $nodes(bs2) $nodes(ms) $bwDL($t) duplex $ns delay $nodes(bs1) $nodes(ms) $propDL($t) duplex $ns delay $nodes(bs2) $nodes(ms) $propDL($t) duplex $ns queue-limit $nodes(bs1) $nodes(ms) 10 $ns queue-limit $nodes(bs2) $nodes(ms) 10 } # RED and TCP parameters
  • 37. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 29 Queue/RED set adaptive_ $adaptive Queue/RED set thresh_ $minth Queue/RED set maxthresh_ $maxth Agent/TCP set window_ $window source web.tcl #Create topology switch $type { gsm - gprs - umts {cell_topo} } set_link_para $type $ns insert-delayer $nodes(ms) $nodes(bs1) [new Delayer] $ns insert-delayer $nodes(ms) $nodes(bs2) [new Delayer] # Set up forward TCP connection if {$flows == 0} { set tcp1 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp) 0] set ftp1 [[set tcp1] attach-app FTP] $ns at 0.8 "[set ftp1] start" } if {$flows > 0} { set tcp1 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp) 0] set ftp1 [[set tcp1] attach-app FTP] $tcp1 set window_ 100 $ns at 0.0 "[set ftp1] start" $ns at 3.5 "[set ftp1] stop" set tcp2 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp) 0] set ftp2 [[set tcp2] attach-app FTP] $tcp2 set window_ 3 $ns at 1.0 "[set ftp2] start" $ns at 8.0 "[set ftp2] stop" } proc stop {} { global nodes opt nf set wrap $opt(wrap) set sid [$nodes($opt(srcTrace)) id] set did [$nodes($opt(dstTrace)) id] set a "out.tr" set GETRC "../../../bin/getrc" set RAW2XG "../../../bin/raw2xg" exec $GETRC -s $sid -d $did -f 0 out.tr | $RAW2XG -s 0.01 -m $wrap -r > plot.xgr exec $GETRC -s $did -d $sid -f 0 out.tr | $RAW2XG -a -s 0.01 -m $wrap >> plot.xgr exec xgraph -x time -y packets plot.xgr & exit 0 } $ns at $stop "stop" $ns run
  • 38. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 30 Output: ns lab5.tcl
  • 39. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 31 Experiment No: 6 Aim:Implement and study the performance of CDMA on NS2/NS3 (Using stack called Call net) or equivalent environment. PERFORMANCE OF CDMA Source Code: # General Parameters set stop 100 ;# Stop time. # Topology set type cdma ;#type of link: # AQM parameters set minth 30 ; set maxth 0 ; set adaptive 1 ;# 1 for Adaptive RED, 0 for plain RED # Traffic generation. set flows 0 ;# number of long-lived TCP flows set window 30 ;# window for long-lived traffic set web 2 ;# number of web sessions # Plotting statics. set opt(wrap) 100 ;# wrap plots? set opt(srcTrace) is ;# where to plot traffic set opt(dstTrace) bs2;# where to plot traffic #default downlink bandwidth in bps set bwDL(cdma) 384000 #default uplink bandwidth in bps set bwUL(cdma) 64000 #default downlink propagation delay in seconds set propDL(cdma) .150 #default uplink propagation delay in seconds set propUL(cdma) .150 set ns [new Simulator] set tf [open out.tr w] $ns trace-all $tf
  • 40. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 32 set nodes(is) [$ns node] set nodes(ms) [$ns node] set nodes(bs1) [$ns node] set nodes(bs2) [$ns node] set nodes(lp) [$ns node] proc cell_topo {} { global ns nodes $ns duplex-link $nodes(lp) $nodes(bs1) 3Mbps 10nodes(ms) DropTail $ns duplex-link $nodes(bs1) $nodes(ms) 1 1 RED $ns duplex-link $nodes(ms) $nodes(bs2) 1 1 RED $ns duplex-link $nodes(bs2) $nodes(is) 3Mbps 50nodes(ms) DropTail puts " cdma Cell Topology" } proc set_link_para {t} { global ns nodes bwUL bwDL propUL propDL buf $ns bandwidth $nodes(bs1) $nodes(ms) $bwDL($t) duplex $ns bandwidth $nodes(bs2) $nodes(ms) $bwDL($t) duplex $ns delay $nodes(bs1) $nodes(ms) $propDL($t) duplex $ns delay $nodes(bs2) $nodes(ms) $propDL($t) duplex $ns queue-limit $nodes(bs1) $nodes(ms) 20 $ns queue-limit $nodes(bs2) $nodes(ms) 20 } # RED and TCP parameters Queue/RED set adaptive_ $adaptive Queue/RED set thresh_ $minth Queue/RED set maxthresh_ $maxth Agent/TCP set window_ $window source web.tcl #Create topology switch $type { cdma {cell_topo} } set_link_para $type $ns insert-delayer $nodes(ms) $nodes(bs1) [new Delayer] $ns insert-delayer $nodes(ms) $nodes(bs2) [new Delayer] # Set up forward TCP connection if {$flows == 0} { set tcp1 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp) 0] set ftp1 [[set tcp1] attach-app FTP] $ns at 0.8 "[set ftp1] start" } if {$flows > 0} { set tcp1 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp) 0] set ftp1 [[set tcp1] attach-app FTP] $tcp1 set window_ 100 $ns at 0.0 "[set ftp1] start"
  • 41. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 33 $ns at 3.5 "[set ftp1] stop" set tcp2 [$ns create-connection TCP/Sack1 $nodes(is) TCPSink/Sack1 $nodes(lp) 0] set ftp2 [[set tcp2] attach-app FTP] $tcp2 set window_ 3 $ns at 1.0 "[set ftp2] start" $ns at 8.0 "[set ftp2] stop" } proc stop { } { global nodes opt nf set wrap $opt(wra p) set sid [$nodes($opt(srcTrace)) id] set did [$nodes($opt(dstTrace)) id]set a "out.tr" set GETRC "../../../bin/getrc" set RAW2XG "../../../bin/raw2xg" exec $GETRC -s $sid -d $did -f 0 out.tr | $RAW2XG -s 0.01 -m $wrap -r > plot.xgrexec $GETRC -s $did - d $sid -f 0 out.tr | $RAW2XG -a -s 0.01 -m $wrap >> plot.xgrexec xgraph -x time -y packets plot.xgr & exit 0 } $ns at $stop "stop" $ns run
  • 42. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 34 Output: ns lab6.tcl CDMA TRACE FILE
  • 43. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 35 Part B 7. Write a program for error detecting code using CRC-CCITT (16- bits). import java.util.Scanner; class CRC { public static void main(String args[]) { Scanner sc=new Scanner(System.in); int m,g[],n,d[],z[],r[],msb,i,j,k; System.out.print(“Enter no. of data bits : “); n=sc.nextInt(); System.out.print(“Enter no. of generator bits : “); m=sc.nextInt(); d=new int[n+m]; g=new int[m]; System.out.print(“Enter data bits : “); for(i=0;i<n;i++) d[i]=sc.nextInt(); System.out.print(“Enter generator bits : “); for(j=0;j<m;j++) g[j]=sc.nextInt(); for(i=0;i<m-1;i++) d[n+i]=0; r=new int[m+n]; for(i=0;i<m;i++) r[i]=d[i]; z=new int[m]; for(i=0;i<m;i++) z[i]=0; for(i=0;i<n;i++) { k=0; msb=r[i]; for(j=i;j<m+i;j++) { if(msb==0) r[j]=xor(r[j],z[k]); else r[j]=xor(r[j],g[k]); k++; } r[m+i]=d[m+i]; } System.out.print(“The code bits added are : “); for(i=n;i<n+m-1;i++) { d[i]=r[i];
  • 44. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 36 System.out.print(d[i]); } System.out.print(“nThe code data is : “); for(i=0;i<n+m-1;i++) { System.out.print(d[i]); } } public static int xor(int x,int y) { if(x==y) return(0); else return(1); } } /*Output of crc cyclic redundancy check program: Enter no. of data bits : 14 Enter no. of generator bits : 4 Enter data bits : 1 1 0 1 0 0 1 1 1 0 1 1 0 0 Enter generator bits : 1 0 1 1 The code bits added are : 100 The code data is : 11010011101100100
  • 45. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 37 8. Write a program to find the shortest path between vertices using bellman-ford algorithm. This is a java program to find shortest path from a single vertex. The Bellman–Ford algorithm is an algorithm that computes shortest paths from a single source vertex to all of the other vertices in a weighted digraph.[1] It is slower than Dijkstra’s algorithm for the same problem, but more versatile, as it is capable of handling graphs in which some of the edge weights are negative numbers. Here is the source code of the Java Program to Use the Bellman-Ford Algorithm to Find the Shortest Path Between Two Vertices Assuming that Negative Size Edges Exist in the Graph. The Java program is successfully compiled and run on a Windows system. The program output is also shown below. 1. 2. package com.hinguapps.graph; 3. 4. import java.util.Scanner; 5. 6. public class BellmanFord 7. { 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. private int private int distances[]; numberofvertices; public static final int MAX_VALUE = 999; public BellmanFord(int numberofvertices) { this.numberofvertices = numberofvertices; distances = new int[numberofvertices + 1]; } public void destination, BellmanFordEvaluation(int source, int 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. int adjacencymatrix[][]) { for (int node = 1; node <= numberofvertices; node++) { distances[node] = MAX_VALUE; } distances[source] = 0; for (int node = 1; node <= numberofvertices - 1; node++) { for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++) 29. { 30. for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++) 31. {
  • 46. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 38 32. if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE) 33. { 34. if (distances[destinationnode] > distances[sourcenode] 35. + adjacencymatrix[sourcenode][destinationnode]) 36. distances[destinationnode] = distances[sourcenode] 37. + adjacencymatrix[sourcenode][destinationnode]; 38. } 39. } 40. } 41. } 42. for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++) 43. { 44. for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++) 45. { 46. if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE) 47. 48. { if (distances[destinationnode] > distances[sourcenode] 49. 50. 51. + adjacencymatrix[sourcenode][destinationnode]) System.out .println("The negative egde cycle"); } } } Graph contains 52. 53. 54. 55. for (int vertex = 1; vertex <= numberofvertices; vertex++) 56. 57. 58. { if (vertex == destination) System.out.println("distance of source " + source + " to " 59. 60. 61. 62. 63. + vertex + " is " + distances[vertex]); } } public static void main(String... arg)
  • 47. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 39 64. { 65. int numberofvertices = 0; 66. int source, destination; 67. Scanner scanner = new Scanner(System.in); 68. System.out.println("Enter the number of vertices"); 69. numberofvertices = scanner.nextInt(); 70. int adjacencymatrix[][] = new int[numberofvertices + 1][numberofvertices + 1]; 71. System.out.println("Enter the adjacency matrix"); 72. for (int sourcenode = 1; sourcenode <= numberofvertices;sourcenode++) 73. { 74. for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++) 75. { 76. adjacencymatrix[sourcenode][destinationnode] = scanner 77. .nextInt(); 78. if (sourcenode == destinationnode) 79. { 80. adjacencymatrix[sourcenode][destinationnode] = 0; 81. continue; 82. } 83. if (adjacencymatrix[sourcenode][destinationnode] == 0) 84. { 85. adjacencymatrix[sourcenode][destinationnode] = MAX_VALUE; 86. } 87. } 88. } 89. System.out.println("Enter the source vertex"); 90. source = scanner.nextInt(); 91. System.out.println("Enter the destination vertex: "); 92. destination = scanner.nextInt(); 93. BellmanFord bellmanford = new BellmanFord(numberofvertices); 94. bellmanford.BellmanFordEvaluation(source, destination, adjacencymatrix); 95. scanner.close(); 96. } 97. } Output:
  • 48. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 40 $ javac BellmanFord.java $ java BellmanFord Output: Enter the number of vertices 6 Enter the adjacency matrix 0 4 0 0 -1 0 0 0 -1 0 -2 0 Enter the source vertex 1 Enter the destination vertex: 4 distance of source 1 to 4 is -6 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 -5 0 3 0 0 0 0 0 0
  • 49. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 41 Experiment No:9 Aim :Using TCP/IP sockets, write a client – server program to make the client send the file name and to make the server send back the contents of the requested file if present. Implement the above program using as message queues or FIFOs as IPC channels . Program File Client import java.io.*; import java.net.*; import java.util.*; class Clientfile { public static void main(String args[]) { Try { BufferedReader in=new BufferedReader(new InputStreamReader(System.in)); Socket clsct=new Socket("127.0.0.1",139); DataInputStream din=new DataInputStream(clsct.getInputStream()); DataOutputStream dout=new DataOutputStream(clsct.getOutputStream()); System.out.println("Enter the file name:"); String str=in.readLine(); dout.writeBytes(str+'n'); System.out.println("Enter the new file name:"); String str2=in.readLine(); String str1,ss; FileWriter f=new FileWriter(str2); char buffer[];
  • 50. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 42 while(true) { str1=din.readLine(); if(str1.equals("-1")) break; System.out.println(str1); buffer=new char[str1.length()]; str1.getChars(0,str1.length(),buffer,0); f.write(buffer); } f.close(); clsct.close(); } catch (Exception e) { System.out.println(e); }}} Server import java.io.*; import java.net.*; import java.util.*; class Serverfile { public static void main(String args[]) { Try { ServerSocket obj=new ServerSocket(139); while(true) {
  • 51. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 43 Socket obj1=obj.accept(); DataInputStream din=new DataInputStream(obj1.getInputStream()); DataOutputStream dout=new DataOutputStream(obj1.getOutputStream()); String str=din.readLine(); FileReader f=new FileReader(str); BufferedReader b=new BufferedReader(f); String s; while((s=b.readLine())!=null) { System.out.println(s); dout.writeBytes(s+'n'); } f.close(); dout.writeBytes("-1n"); } } catch(Exception e) { System.out.println(e);} } } Output File content Computer networks jhfcgsauf jbsdava jbvuesagv client Enter the file name: sample.txt
  • 52. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 44 server Computer networks jhfcgsauf jbsdava jbvuesagv client Enter the new file name: net.txt Computer networks jhfcgsauf jbsdava jbvuesagv Destination file Computer networks jhfcgsauf jbsdava jbvuesagv
  • 53. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 45 Experiment No:10 Aim: Write a program on datagram socket for client/server to display the messages on client side, typed at the server side. Program UDPserver.java import java.io.*; import java.net.*; class UDPserver { public static DatagramSocket ds; public static byte buffer[]=new byte[1024]; public static int clientport=789,serverport=790; public static void main(String args[])throws Exception { ds=new DatagramSocket(clientport); System.out.println("press ctrl+c to quit the program"); BufferedReader dis=new BufferedReader(new InputStreamReader(System.in)); InetAddress ia=InetAddress.geyLocalHost(); while(true) { DatagramPacket p=new DatagramPacket(buffer,buffer.length); ds.receive(p); String psx=new String(p.getData(),0,p.getLength()); System.out.println("Client:" + psx); System.out.println("Server:"); String str=dis.readLine(); if(str.equals("end"))
  • 54. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 46 break; buffer=str.getBytes(); ds.send(new DatagramPacket(buffer,str.length(),ia,serverport)); } } } UDPclient.java import java .io.*; import java.net.*; class UDPclient { public static DatagramSocket ds; public static int clientport=789,serverport=790; public static void main(String args[])throws Exception { byte buffer[]=new byte[1024]; ds=new DatagramSocket(serverport); BufferedReader dis=new BufferedReader(new InputStreamReader(System.in)); System.out.println("server waiting"); InetAddress ia=InetAddress.getLocalHost(); while(true) { System.out.println("Client:"); String str=dis.readLine(); if(str.equals("end")) break;
  • 55. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 47 buffer=str.getBytes(); ds.send(new DatagramPacket(buffer,str.length(),ia,clientport)); DatagramPacket p=new DatagramPacket(buffer,buffer.length); ds.receive(p); String psx=new String(p.getData(),0,p.getLength()); System.out.println("Server:" + psx); } } } OUTPUT Server C:Program FilesJavajdk1.5.0bin>javac UDPserver.java C:Program FilesJavajdk1.5.0bin>java UDPserver press ctrl+c to quit the program Client:Hai Server Server: Hello Client Client:How are You Server: I am Fine Client C:Program FilesJavajdk1.5.0bin>javac UDPclient.java C:Program FilesJavajdk1.5.0bin>java UDPclient server waiting Client: Hai Server Server:Hello Clie
  • 56. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 48 Client: How are You Server:I am Fine Client: End
  • 57. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 49 11. Write a program for simple RSA algorithm to encrypt and decrypt the data. Before we can start writing the code for RSA algorithm using the programming languages like C and JAVA, lets first understand what the algorithm is... Basically RSA is cryprograpic algorithm which is meant to encrypt the data, generally used in network security applications while we are sending the data from one source to destination. ..The concept of RSA algorithm starts with a two key concepts, it uses two keys(asymmetric keys) one is considered as the public key and another is a private key... It was developed because using the symmetric encryption algorithm is easy but the key distribution is difficult, so the concept of two key concept appears to be more efficient... The whole algorithm depends on the fact that "It is not possible to judge the another key when attack gets one key" Here in two keys, one key is taken as the public key another as a private key..public key is available for everyone to access, so whenever sender want to send the data to receiver, he uses the public key of receiver(as it is available for use to all) and encrypts the data using the key, this encrypted data is called cipher text. when receiver receives the cipher text, he can decrypt the data using his private key Here even if the attacker knows the encryption algorithm, he cant do anything until the keys are available....This is theoretical part of RSA.. as we know this forum always try to present implementation details along with description, here am writing the steps used in this algorithm Step 1 : Select two prime nos – p & q such as p!=q Step 2 : Calculate n as product of p & q, i.e. n=pq Step 3 : Calculate m as product of (p-1) & (q-1) i.e. m = (p-1)(q-1) Step 4 : Select any integer e<m such that it is co-prime to m, co-prime means gcd(e,m) =1 Step 5 : Calculate d such that de mod m = 1 , i.e. d = e^-1 mod m Step 6: The public key is {e,n) The private key is {d,n} So these are the keys, now if you want to preform some encryption operation using these keys here are the steps, if you have a text P..its encrypted version(cipher text C is) C = P^e mod n To decrpty it back to plain text use P = C^d mod n Example:- 1. Select two prime nos – p=7 & q = 17 2. Calculate n as product of p & q, n= 7 X 17=119 3. Calculate m as product of (p-1) & (q-1) , m= 6 X 16 = 96 4. Select any integer e<m such that it is relatively co-prime to m, which in this case, e = 5 5. Calculate d such that de mod m = 1 , i.e. d X e = 1 mod 96 and d < 96 Here ,d=77 as 77 X 5 = 385 = 4 x 96 + 1 6. The public key is { 5,119} and private key is{ 77,119}
  • 58. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 50 7. Taking plaintext as P=19 and using the public key we get the ciphertext as C=66. 8. Similarly, we use decryption and get the same plaintext using RSA algorithm. 1. Import java.math.BigInteger; Import java.security.*; Import java.security.spec.*; Import java.io.*; Import javax.crypto.Cipher; Public class RSA { Public staticvoid main(String args[]) { String srci=""; try{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("Please enter any string you want to encrypt"); srci=br.readLine(); } catch(IOException ioe) { System.out.println(ioe.getMessage()); } try{ KeyPairGenerator kpg=KeyPairGenerator.getInstance("RSA"); kpg.initialize(512);//initialize key pairs to 512 bits ,you can also take 1024 or 2048 bits KeyPair kp=kpg.genKeyPair(); PublicKey publi=kp.getPublic(); Cipher cipher =Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE,publi); byte[]src=srci.getBytes();//converting source data into byte array byte[] cipherData = cipher.doFinal(src);//use this method to finally encrypt data String srco=new String(cipherData);//converting byte array into string System.out.println(); System.out.println("Encrypted data is:-"+srco); PrivateKey privatei=kp.getPrivate();//Generating private key Cipher cipheri=Cipher.getInstance("RSA");//Intializing 2nd instance of Cipher class cipheri.init(Cipher.DECRYPT_MODE, privatei);//Setting to decrypt_mode byte[] cipherDat = cipheri.doFinal(cipherData);//Finally decrypting data String decryptdata=new String(cipherDat); System.out.println("Decrypted data:-"+decryptdata); }
  • 59. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET, Mukka Page 51 catch(Exception e) { System.out.println(e.getMessage()); } } } package com.sanfoundry.setandstring; 2. 3. import java.io.DataInputStream; 4. import java.io.IOException; 5. import java.math.BigInteger; 6. import java.util.Random; 7. 8. public class RSA 9. { 10. private BigInteger p; 11. private BigInteger q; 12. private BigInteger N; 13. private BigInteger phi; 14. private BigInteger e; 15. private BigInteger d; 16. private int bitlength = 1024; 17. private Random r; 18. 19. public RSA() 20. { 21. r = new Random(); 22. p = BigInteger.probablePrime(bitlength, r); 23. q = BigInteger.probablePrime(bitlength, r); 24. N = p.multiply(q); 25. phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE)); 26. e = BigInteger.probablePrime(bitlength / 2, r); 27. while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0) 28. { 29. e.add(BigInteger.ONE); 30. } 31. d = e.modInverse(phi); 32. } 33. 34. public RSA(BigInteger e, BigInteger d, BigInteger N) 35. { 36. this.e = e; 37. this.d = d; 38. this.N = N;
  • 60. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET, Mukka Page 52 39. } 40. 41. @SuppressWarnings("deprecation") 42. public static void main(String[] args) throws IOException 43. { 44. RSA rsa = new RSA(); 45. DataInputStream in = new DataInputStream(System.in); 46. String teststring; 47. System.out.println("Enter the plain text:"); 48. teststring = in.readLine(); 49. System.out.println("Encrypting String: " + teststring); 50. System.out.println("String in Bytes: " 51. + bytesToString(teststring.getBytes())); 52. // encrypt 53. byte[] encrypted = rsa.encrypt(teststring.getBytes()); 54. // decrypt 55. byte[] decrypted = rsa.decrypt(encrypted); 56. System.out.println("Decrypting Bytes: " + 57. bytesToString(decrypted)); System.out.println("Decrypted String: " + new 58. String(decrypted)); } 59. 60. private static String bytesToString(byte[] encrypted) 61. { 62. String test = ""; 63. for (byte b : encrypted) 64. { 65. test += Byte.toString(b); 66. } 67. return test; 68. } 69. 70. // Encrypt message 71. public byte[] encrypt(byte[] message) 72. { 73. return (new BigInteger(message)).modPow(e, N).toByteArray(); 74. } 75. 76. // Decrypt message 77. public byte[] decrypt(byte[] message) 78. { 79. return (new N).toByteArray(); BigInteger(message)).modPow(d,
  • 61. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET, Mukka Page 53 80. 81. } } $ javac RSA.java $ java RSA Enter the plain text: Sanfoundry Encrypting String: Sanfoundry String in Bytes: 8397110102111117110100114121 Decrypting Bytes: 8397110102111117110100114121 Decrypted String: Sanfoundry Output:
  • 62. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 54 12. Write a program for congestion control using leaky bucket algorithm. Aim: TO IMPLEMENT LEAKY BUCKET ALGORITHM IN JAVA filename:Licky.java */ import java.io.*; import java.util.*; class Queue { int q[],f=0,r=0,size;void insert(int n) { Scanner in = new Scanner(System.in);q=new int[10]; for(int i=0;i<n;i++) { System.out.print("nEnter " + i + " element: ");int ele=in.nextInt(); if(r+1>10) { System.out.println("nQueue is full nLost Packet: "+ele);break; } else { r++; q[i]=ele; } } } void delete() { Scanner in = new Scanner(System.in);Thread t=new Thread(); if(r==0) System.out.print("nQueue empty "); { { try { } else for(int i=f;i<r;i++) t.sleep(1000); catch(Exception e){} System.out.print("nLeaked Packet: "+q[i]);f++; } } System.out.println(); } }
  • 63. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 55 class Licky extends Thread { public static void main(String ar[])throws Exception { Queue q=new Queue(); Scanner src=new Scanner(System.in); System.out.println("nEnter the packets to be sent:");int size=src.nextInt(); q.insert(size); q.delete(); } } OUTPUT bash-3.00$ javac Licky.javabash-3.00$ java Licky Enter the packets to be sent:11 Enter 0 element: 1 Enter 1 element: 0 Enter 2 element: 2 Enter 3 element: 3 Enter 4 element: 4 Enter 5 element: 5 Enter 6 element: 6 Enter 7 element: 7 Enter 8 element: 8 Enter 9 element: 9 Enter 10 element: 10 Queue is full Lost Packet: 10 Leaked Packet: 1 Leaked Packet: 0 Leaked Packet: 2 Leaked Packet: 3 Leaked Packet: 4 Leaked Packet: 5 Leaked Packet: 6 Leaked Packet: 7 Leaked Packet: 8 Leaked Packet: 9
  • 64. Computer Networks Lab (19CSL56) Dept of C.S & E. SUCET,Mukka Page 56 1. What is socket? How it is implemented? 2. What are the different system calls on client side and server side implementation? 3. How to convert single client into multiple clients handling in server? 4. What are the differences between SOCK_STREAM, SOCK_DGRAM, and SOCK_RAM?What is their level of implementation? 5. Explain need of sock adder_ in structure and IN ADDR_ANY. 6. What is FIFO? How to implement Multiple FIFOs. Disadvantages of FIFO? 7. Which are the different IPC Primitives? Explain Why IPC Primitives are required? 8. Explain the purpose of RS algorithm? What is Public and Private Key? How to find publicand private key in RSA algorithm? 9. List some Cryptographic algorithms? 10. What is congestion? Explain leaky bucket and token bucket algorithm? What are itsdisadvantages of each? 11. List other congestion control algorithm. 12. What are the disadvantages of RSA Algorithm? 13. What is the need for routing protocols? List some routing protocols. Which are commonrouting algorithms used by routing protocols 14. Disadvantages of Distance vector routing. Explain the method to overcome suchdisadvantage. 15. What is CRC? What is the need for CRC? Which Layer it is implemented? 16. Can CRC be employed for error correction if so how. 17. Explain steps of error correction and error detection. What is encoding and decoding, why it isrequired? 18. What is Hamming code? Can it be used for error detection and correction how? 19. What are linear block codes? Explain their advantages. 20. What is protocol? List some protocols. How to modify existing protocol? 21. Difference between TCP/IP and OSI Layer Model? 22. Difference between Router, Bridge, Gateway channel. In which layer it is used? 23. Difference between hub and switch. Which is more compatible and reliable? 24. Explain various Ethernet standards. 25. Difference between IP and MAC address. 26. In which layer ATM protocol is used? Explain the purpose. 27. In Which layer or protocol which converts IP to MAC Address. 28. Which are the different collision detection protocols? 29. Which are the different channelization protocol and explain their needs? 30. Explain term error rate, bandwidth, throughput transmission delay, BER, Interarrival time.What is unit of bandwidth? 31. What is congestion/contention Window? How it is constructed and managed and by whichlayer? 32. What is ping utility? How it is implemented? 33. Which are different parameters in ICMP protocol? Explain purpose of ICMP. 34. List and explain different link types. Differentiate its characteristics. 35. List TCP and UDP Properties? 36. Why TCP is more reliable than UDP? 37. Is data rate and bandwidth are same? 38. Difference between ESS and BSS. Explain various elements composing the structure of BSS. 39. Explain various factors that results in congestion and collision. 40. Explain QOS and different measures taken for implementing QOS in network. 41. List different N/W topologies. 42. Difference between Data rate versus Throughput. 43. List the meaning and term used for data in different layers of TCP/IP protocol suite. VIVA QUESTIONS