Computer-Network-Lab Manual 18CSL57 - 22-10-2021
Computer-Network-Lab Manual 18CSL57 - 22-10-2021
18CSL57
DEPARTMENT OF COMPUTERSCIENCE AND ENGINEERING
VISION
MISSION
The Department of Computer Science And Engineering will Provide Transformative
education and Research to create, Contribute innovators and Leaders for society and
Industry
V SEMESTER
18CSL57
o For laboratories having only one part: Students are allowed to pick one experiment
from the lot with equal opportunity.
o For laboratories having PART A and PART B: Students are allowed to pick one experi-
ment from PART A and one experiment from PART B, with equal opportunity.
Change of experiment is allowed only once and marks allotted for procedure to be made zero of
the changed part only.
Marks Distribution (Courseed to change in accoradance with university regulations)
i) For laboratories having only one part – Procedure + Execution + Viva-Voce: 15+70+15 =
100 Marks
j) For laboratories having PART A and PART B
i. Part A – Procedure + Execution + Viva = 6 + 28 + 6 = 40 Marks
ii. Part B – Procedure + Execution + Viva = 9 + 42 + 9 = 60 Marks
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 behaviours.
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]
• 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}
{ ...
...
}
}
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
set ns [new Simulator]
which is thus the first line in the tcl script? This line declares a new variable as using the set
command, you can call this variable as you wish, In general people declares it as ns because
it is an instance of the Simulator class, so an object the code [new Simulator] is indeed the
installation of the class Simulator using the reserved word new.
In order to have output files with data on the simulation (trace files) or files used
for visualization (nam files), we need to create the files using “open” command:
$ns flush-trace
Close $tracefile1
Close $namfile
Exit 0
The word proc declares a procedure in this case called finish and without arguments.
The word global is used to tell that we are using variables declared outside the procedure.
The simulator method “flush-trace” will dump the traces on the respective files. The tcl
command “close” closes the trace files defined before and exec executes the nam program
for visualization. The command exit will end the application and return the number 0 as
status to the system. Zero is the default for a clean exit. Other values can be used to say that
is a exit because something fails.
At the end of ns program, we should call the procedure “finish” and specify at what
time the termination should occur. For example,
$ns at 125.0 “finish”
will be used to call “finish” at time 125sec.Indeed, the at method of the simulator allows us
to schedule events explicitly.
The simulation can then begin using the command
$ns run
In our case, if the buffer capacity of the output queue is exceeded then the last packet to
arrive is dropped. Many alternative options exist, such as the RED (Random Early Discard)
mechanism, the FQ (Fair Queuing), the DRR (Deficit Round Robin), the stochastic Fair
Queuing (SFQ) and the CBQ (which including a priority and a round-robin scheduler).
In ns, an output queue of a node is implemented as a part of each link whose input is
that node. We should also define the buffer capacity of the queue related to each link. An
example would be:
#set Queue Size of link (n0-n2) to 20
The command $ns attach-agent $n0 $tcp defines the source node of the
tcp connection.
The Command Defines the behaviour of the destination node of TCP and assigns to it a
pointer called sink.
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
$ns at 0.1 “$cbr start”
Event Time From To PKT PKT Flags Fid Src Dest Seq Pkt
Node Node Type Size Addr Addr Num id
1. The first field is the event type. It is given by one of four possible symbols r, +, -, d
which correspond respectively to receive (at the output of the link), enqueued, dequeued
and dropped.
2. The second field gives the time at which the event occurs.
3. Gives the input node of the link at which the event occurs.
4. Gives the output node of the link at which the event occurs.
5. Gives the packet type (eg CBR or TCP)
6. Gives the packet size
7. Some flags
8. This is the flow id (fid) of IPv6 that a user can set for each flow at the input OTcl script
one can further use this field for analysis purposes; it is also used when specifying stream
color for the NAM display.
9. This is the source address given in the form of “node.port”.
10. This is the destination address, given in the same form.
11. This is the network layer protocol’s packet sequence number. Even though UDP
implementations in a real network do not use sequence number, ns keeps track of UDP
packet sequence number for analysis purposes
12. The last field shows the unique id of the packet.
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 up to 64 independent data
sets using different colours and line styles for each set. It annotates the graph with a title, axis
labels, grid lines or tick marks, grid labels and a legend.
Syntax:
Xgraph [options] file-name
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.
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 their 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
{ count =count+1
printf “ %3f %20s %-12s %d\n”, count,$2,$3,$6 }’ empn.lst
THE –f OPTION: STORING awk PROGRAMS INA FILE
You should hold large awk programs in separate file and provide them with the awk
extension for easier identification. Let’s first store the previous program in the file
empawk.awk:
$ cat empawk.awk
Observe that this time we haven’t used quotes to enclose the awk program. You can
now use awk with the –f filename option to obtain the same output:
Awk –F”|” –f empawk.awk empn.lst
BUILT-IN VARIABLES
Awk has several built-in variables. They are all assigned automatically, though it is
also possible for a user to reassign some of them. You have already used NR, which signifies
the record number of the current line. We’ll now have a brief look at some of the other
variable. The FS Variable: as stated elsewhere, awk uses a contiguous string of spaces as the
default field delimiter. FS redefines this field separator, which in the sample database
happens to be the |. When used at all, it must occur in the BEGIN section so that the body of
the program knows its value before it starts processing:
BEGIN {FS=”|”}
This is an alternative to the –F option which does the same thing.
The OFS Variable: when you used the print statement with comma-separated arguments,
each argument was separated from the other by a space. This is awk’s default output field
separator, and can reassigned using the variable OFS in the BEGIN section:
BEGIN { OFS=”~” }
When you reassign this variable with a ~ (tilde), awk will use this character for delimiting
the print arguments. This is a useful variable for creating lines with delimited fields.
The NF variable: NF comes in quite handy for cleaning up a database of lines that don’t
contain the right number of fields. By using it on a file, say emp.lst, you can locate those
lines not having 6 fields, and which have crept in due to faulty data entry:
$awk ‘BEGIN {FS = “|”}
NF! =6 {
Print “Record No “, NR, “has”, “fields”}’ empx.lst
The FILENAME Variable: FILENAME stores the name of the current file being processed.
Like grep and sed, awk can also handle multiple filenames in the command line. By default,
awk doesn’t print the filename, but you can instruct it to do so:
‘$6<4000 {print FILENAME, $0 }’
With FILENAME, you can device logic that does different things depending on the file that
is processed.
NS2 Installation
• NS2 is a free simulation tool.
• It runs on various platforms including UNIX (or Linux), Windows, and Mac systems.
• NS2 source codes are distributed in two forms: the all-in-one suite and the
component-wise.
• ‘all-in-one’ package provides an “install” script which configures the NS2 environment and
creates NS2 executable file using the “make” utility.
“/opt/ns-allinone-2.33/otcl-1.13:/opt/ns-allinone-2.33/lib”
➢ In the next line type “TCL_LIBRARY=$TCL_LIBRARY:” and paste the path which is
present in previous terminal i.e Important Notices section (2)
“/opt/ns-allinone-2.33/tcl8.4.18/library”
➢ In the next line type “export LD_LIBRARY_PATH”
➢ In the next line type “export TCL_LIBRARY”
➢ The next two lines are already present the file “export PATH” and “unset USERNAME”
➢ Save the program ( ESC + shift : wq and press enter )
➢ Now in the terminal where we have opened .bash_profile file, type the following
command to check if path is updated correctly or not
[root@localhost ~] # vi .bash_profile
[root@localhost ~] # source .bash_profile
➢ If path is updated properly, then we will get the prompt as shown
below [root@localhost ~] #
➢ Now open the previous terminal where you have installed ns
[root@localhost ns-allinone-2.33] #
➢ Here we need to configure three packages “ns-2.33”, “nam-1.13” and “xgraph-12.1”
➢ First, configure “ns-2.33” package as shown below
[root@localhost ns-allinone-2.33] # cd ns-2.33
[root@localhost ns-2.33] # ./configure
[root@localhost ns-2.33] # make clean
[root@localhost ns-2.33] # make
[root@localhost ns-2.33] # make install
[root@localhost ns-2.33] # ns
%
➢ If we get “%” symbol it indicates that ns-2.33 configuration was successful.
➢ Second, configure “nam-1.13” package as shown below
[root@localhost ns-2.33] # cd . . [root@localhost
ns-allinone-2.33] # cd nam-1.13 [root@localhost
nam-1.13] # ./configure [root@localhost nam-
1.13] # make clean [root@localhost nam-1.13] #
make [root@localhost nam-1.13] # make install
[root@localhost nam-1.13] # ns
%
➢ If we get “%” symbol it indicates that nam-1.13 configuration was successful.
➢ Third, configure “xgraph-12.1” package as shown below
[root@localhost nam-1.13] # cd . . [root@localhost
ns-allinone-2.33] # cd xgraph-12.1 [root@localhost
xgraph-12.1] # ./configure [root@localhost xgraph-
12.1] # make clean [root@localhost xgraph-12.1] #
make [root@localhost xgraph-12.1] # make install
[root@localhost xgraph-12.1] # ns
%
This completes the installation process of “NS-2” simulator.
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.
proc finish {} { /* provide space b/w proc and finish and all are in small case */
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam p1.nam &
exit 0
}
$ns duplex-link $n0 $n2 200Mb 10ms DropTail /*Letter M is capital Mb*/
$ns duplex-link $n1 $n2 100Mb 5ms DropTail /*D and T are capital*/ $ns
$ns duplex-link $n2 $n3 1Mb 1000ms DropTail
$ns run
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("%s\t%s\n",$5,$11);
}
}
/*immediately after END should open braces ‘{‘
END{
printf("The number of packets dropped =%d\n",c);
}
proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam p2.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"
AWK file (Open a new editor using “vi command” and write awk file and save with
“.awk” extension)
BEGIN{
drop=0;
}
{
if($1=="d")
{
drop++;
}
}
END{
printf("Total number of %s packets dropped due to congestion =%d\n",$5,drop);
}
Topology
Note:
Vary the bandwidth and queue size between the nodes n0-n2 , n2-n4. n6-n2 and n2- n5
and see the number of packets dropped at the nodes.
3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and
plot congestion window for different source / destination.
$ns make-lan "$n0 $n1 $n2 $n3 $n4" 100Mb 100ms LL Queue/DropTail Mac/802_3
$ns duplex-link $n4 $n5 1Mb 1ms DropTail
proc finish { } {
global ns nf tf
$ns flush-trace
close $tf
close $nf
exec nam p3.nam &
exit 0
}
AWK file (Open a new editor using “vi command” and write awk file and save with
“.awk” extension)
BEGIN {
}
{
if($6=="cwnd_") # don’t leave space after writing cwnd_
printf("%f\t%f\t\n",$1,$7); # you must put \n in printf
}
END {
}
Steps for execution
1) Open vi editor and type program. Program name should have the extension “ .tcl ”
[root@localhost ~]# vi p3.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 p3.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 p3.tcl
6) After simulation is completed run awk file to see the output ,
i. [root@localhost~]# awk –f p3.awk file1.tr > a1
ii. [root@localhost~]# awk –f p3.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 p3.tr
Topology
4. Implement simple ESS and with transmitting nodes in wire-less LAN by simulation
and determine the performance with respect to transmission of packets.
create-god 3
$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
proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam p4.nam &
exit 0
}
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
}
}
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)));
}
5. Implement and study the performance of GSM on NS2/NS3 (Using MAC layer)
or equivalent environment.
GSM can be implemented on all the versions of NS2 (Since year 2004: ns-2.27, and later
versions of NS2)
Design:
jss@jss-OptiPlex-3046:~/ns-allinone-2.35$ cd ns-2.35/
jss@jss-OptiPlex-3046:~/ns-allinone-2.35/ns-2.35$ cd tcl/
jss@jss-OptiPlex-3046:~/ns-allinone-2.35/ns-2.35/tcl$ cd ex/
jss@jss-OptiPlex-3046:~/ns-allinone-2.35/ns-2.35/tcl/ex$ cd wireless-scripts/
# General Parameters
set stop 100 ;# Stop time.
# Topology
set type gsm ;#type of link:
# AQM parameters
set minth 0 ;
set maxth 30 ;
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
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
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]
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
6. Implement and study the performance of CDMA on NS2/NS3 (Using stack called
Call net) or equivalent environment.
CDMA can be implemented on all the versions of NS2 (Since year 2004: ns-2.27, and later
versions of NS2)
Design:
Note: Save the program in the following path.
jss@jss-OptiPlex-3046:~$ cd ns-allinone-2.35/
jss@jss-OptiPlex-3046:~/ns-allinone-2.35$ cd ns-2.35/
jss@jss-OptiPlex-3046:~/ns-allinone-2.35/ns-2.35$ cd tcl/
jss@jss-OptiPlex-3046:~/ns-allinone-2.35/ns-2.35/tcl$ cd ex/
jss@jss-OptiPlex-3046:~/ns-allinone-2.35/ns-2.35/tcl/ex$ cd wireless-scripts/
jss@jss-OptiPlex-3046:~/ns-allinone-2.35/ns-2.35/tcl/ex/wireless-scripts$ gedit p6.tcl
# General Parameters
set stop 100 ;# Stop time.
# Topology
set type cdma ;#type of link:
# AQM parameters
set minth 0 ;
set maxth 30 ;
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
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]
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
PART-B
Java is a general-purpose computer programming language that is simple, concurrent,
class-based, object-oriented language. The compiled Java code can run on all platforms that
support Java without the need for recompilation hence Java is called as "write once, run
anywhere" (WORA).The Java compiled intermediate output called “byte-code” that can run
on any Java virtual machine (JVM) regardless of computer architecture. The language derives
much of its syntax from C and C++, but it has fewer low-level facilities than either of them.
In Linux operating system Java libraries are preinstalled. It’s very easy and convenient
to compile and run Java programs in Linux environment. To compile and run Java Program
is a two-step process:
The Java compiler (Javac) compiles java program and generates a byte-code with the
same file name and .class extension.
2. Run Java program from Command Prompt
[root@host ~]# java Filename
The java interpreter (Java) runs the byte-code and gives the respective output. It is
important to note that in above command we have omitted the .class suffix of the
byte-code (Filename.class).
1. Write a program for error detecting code using CRC-CCITT (16- bits).
Whenever digital data is stored or interfaced, data corruption might occur. Since the
beginning of computer science, developers have been thinking of ways to deal with this type of
problem. For serial data they came up with the solution to attach a parity bit to each sent byte.
This simple detection mechanism works if an odd number of bits in a byte changes, but an even
number of false bits in one byte will not be detected by the parity check. To overcome this
problem developer have searched for mathematical sound mechanisms to detect multiple false
bits. The CRC calculation or cyclic redundancy check was the result of this. Nowadays CRC
calculations are used in all types of communications. All packets sent over a network connection
are checked with a CRC. Also each data block on your hard disk has a CRC value attached to it.
Modern computer world cannot do without these CRC calculations. So let's see why they are so
widely used. The answer is simple; they are powerful, detect many types of errors and are
extremely fast to calculate especially when dedicated hardware chips are used.
The idea behind CRC calculation is to look at the data as one large binary number. This
number is divided by a certain value and the remainder of the calculation is called the CRC.
Dividing in the CRC calculation at first looks to cost a lot of computing power, but it can be
performed very quickly if we use a method similar to the one learned at school. We will as an
example calculate the remainder for the character 'm'—which is 1101101 in binary notation— by
dividing it by 19 or 10011. Please note that 19 is an odd number. This is necessary as we will see
further on. Please refer to your schoolbooks as the binary calculation method here is not very
different from the decimal method you learned when you were young. It might only look a little
bit strange. Also notations differ between countries, but the method is similar.
With decimal calculations you can quickly check that 109 divided by 19 gives a quotient of 5
with 14 as the remainder. But what we also see in the scheme is that every bit extra to check
only costs one binary comparison and in 50% of the cases one binary subtraction. You can
easily increase the number of bits of the test data string—for example to 56 bits if we use our
example value "Lammert"—and the result can be calculated with 56 binary comparisons and
an average of 28 binary subtractions. This can be implemented in hardware directly with only
very few transistors involved. Also software algorithms can be very efficient.
All of the CRC formulas you will encounter are simply checksum algorithms based on
modulo-2 binary division where we ignore carry bits and in effect the subtraction will be
equal to an exclusive or operation. Though some differences exist in the specifics across
different CRC formulas, the basic mathematical process is always the same:
• The message bits are appended with c zero bits; this augmented message is the dividend
• A predetermined c+1-bit binary sequence, called the generator polynomial, is the divisor
• The checksum is the c-bit remainder that results from the division operation
Table 1 lists some of the most commonly used generator polynomials for 16- and 32-bit
CRCs. Remember that the width of the divisor is always one bit wider than the remainder.
So, for example, you’d use a 17-bit generator polynomial whenever a 16-bit checksum is
required.
Checksum
16 bits 16 bits 32 bits
Width
Generator
10001000000100001 11000000000000101 100000100110000010001110110110111
Polynomial
import java.io.*;
import java.*;
public class p7
{
for(int i=0;i<app_message.length;i++)
{
trans_message[i]=(app_message[i]^rem[i]);
}
import java.util.Scanner;
public class p8
{
private int d[];
private int num_ver;
public static final int max_value=999;
public p8(int num_ver)
{
this.num_ver=num_ver;
d=new int [num_ver+1];
}
public void bellmanfordevaluation(int source,int a[][])
{
for(int node=1; node<=num_ver; node++)
{
d[node]=max_value;
}
d[source]=0;
for(int node=1; node<=num_ver-1; node++)
{
for(int sn=1;sn<=num_ver;sn++)
{
for(int dn=1;dn<=num_ver;dn++)
{
if(a[sn][dn]!=max_value)
{
if(d[dn]>d[sn]+a[sn][dn])
d[dn]=d[sn]+a[sn][dn];
}
}
}
}
for(int sn=1;sn<=num_ver;sn++)
{
for(int dn=1;dn<=num_ver;dn++)
{
if(a[sn][dn]!=max_value)
{ if(d[dn]>d[sn]+a[sn][dn])
System.out.println("the graph contains -ve edge cycle");
}
}
}
for(int vertex=1;vertex<=num_ver;vertex++)
{
System.out.println("disten of
source"+source+"to"+vertex+"is"+d[vertex]);
}
}
public static void main(String args[])
{
int num_ver=0;
int source;
Scanner scanner=new Scanner(System.in);
System.out.println("enter the num of vertices");
num_ver=scanner.nextInt();
int a[][]=new int [num_ver+1] [num_ver+1];
System.out.println("enter the adjacency matrix:");
for(int sn=1;sn<=num_ver;sn++)
{
for(int dn=1;dn<=num_ver;dn++)
{ a[sn][dn]=scanner.nextInt();
if(sn==dn)
{ a[sn][dn]=1;
continue;
}
if(a[sn][dn]==0)
{
a[sn][dn]=max_value;
}
}
}
System.out.println("enter the source vertex");
source=scanner.nextInt();
p8 b=new p8(num_ver);
b.bellmanfordevaluation(source,a);
scanner.close();
}
}
Input graph:
5
A B
3
4
C D
3. 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.
Source Code:
TCP Client
import java.net.*;
import java.io.*;
import java.util.Scanner;
public class p9tcpclient
{
public static void main(String args[])
{
Socket s;
while(true)
{
try
{
s=new Socket("127.0.0.1",3000);
OutputStream ostream=s.getOutputStream();
System.out.println("enter filename");
Scanner input= new Scanner(System.in);
String fname= input.nextLine();
PrintWriter pwrite = new PrintWriter(ostream, true);
pwrite.println(fname);
InputStream istream= s.getInputStream();
Scanner cRead= new Scanner (new InputStreamReader(istream));
while(cRead.hasNext())
System.out.println(cRead.nextLine());
pwrite.close();
s.close();
}
catch(Exception e)
{ e.printStackTrace();}
}
}
}
TCP Server
import java.util.Scanner;
import java.net.*;
import java.io.*;
public class p9tcpserver
{
public static void main(String args[]) throws IOException
{
ServerSocket ss=null;
Socket s=null;
try
{
ss=new ServerSocket(3000);
}
catch(Exception e)
{ e.printStackTrace();
}
while(true)
{
try
{
System.out.println("SERVER READY!!..");
s=ss.accept();
System.out.println("CLIENT CONNECTED..");
InputStream istream = s.getInputStream();
Scanner fread= new Scanner(new InputStreamReader(istream));
String fileName= fread.nextLine();
System.out.println("reading contents of "+fileName);
Scanner contentRead= new Scanner(new FileReader(fileName));
OutputStream ostream= s.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream,true);
String str;
while(contentRead.hasNext())
pwrite.println(contentRead.nextLine());
pwrite.close();
s.close();
}
catch(FileNotFoundException e1)
{
System.out.println("file not found");
OutputStream ostream =s.getOutputStream();
PrintWriter pwrite= new PrintWriter(ostream,true);
pwrite.close();
}
catch(Exception e)
{}
}
}
}
Source Code:
UDP Client
import java.util.Scanner;
import java.net.*;
import java.io.*;
public class p10udpclient
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
DatagramSocket skt;
try
{
skt=new DatagramSocket();
InetAddress host=InetAddress.getByName("127.0.0.1");
int s_port=3780;
while(true)
{
System.out.println("Client");
String msg=in.nextLine();
byte[] b = msg.getBytes();
DatagramPacket request=new DatagramPacket(b,b.length,host,s_port);
skt.send(request);
byte buffer[]=new byte[1024];
DatagramPacket reply=new DatagramPacket(buffer,buffer.length);
skt.receive(reply);
System.out.println("Server:"+new String(reply.getData()));
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
UDP Server
import java.util.Scanner;
import java.net.*;
import java.io.*;
public class p10udpserver
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
DatagramSocket skt=null;
try
{
skt=new DatagramSocket(3780);
System.out.println("Server is ready");
while(true)
{
byte buffer[]=new byte[1024];
DatagramPacket req= new DatagramPacket(buffer,buffer.length);
skt.receive(req);
String msg=new String(req.getData());
System.out.println("Client:" +msg);
System.out.println("Server");
String m=in.nextLine();
byte[] sendmsg = m.getBytes();
DatagramPacket reply=new
DatagramPacket(sendmsg,sendmsg.length,req.getAddress(),req.getPort())
;
skt.send(reply);
}
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Encryption
Sender A does the following:-
Decryption
Recipient B does the following:-
Source Code:
RSA Key Generation
import java.util.*;
import java.math.BigInteger;
import java.lang.*;
class p11RSAkeygen
{
public static void main(String[] args)
{
int pubkey=Integer.parseInt(args[0]);
BigInteger bigB_n=bigB_p.multiply(bigB_q);
BigInteger bigB_p_1_q_1=bigB_p_1.multiply(bigB_q_1);
while(true)
{
{
break;
}
pubkey++;
}
BigInteger bigB_pubkey=new BigInteger(""+pubkey);
BigInteger bigB_prvkey=bigB_pubkey.modInverse(bigB_p_1_q_1);
System.out.println("public key : "+bigB_pubkey+","+bigB_n);
System.out.println("private key : "+bigB_prvkey+","+bigB_n);
}
}
import java.math.BigInteger;
import java.util.*;
class p11RSAEncDec
{
public static void main(String[] args)
{
The main concept of the leaky bucket algorithm is that the output
data flow remains constant despite the variant input traffic, such as the
water flow in a bucket with a small hole at the bottom. In case the bucket
contains water (or packets) then the output flow follows a constant rate,
while if the bucket is full any additional load will be lost because of
spillover. In a similar way if the bucket is empty the output will be zero.
From network perspective, leaky bucket consists of a finite queue
(bucket) where all the incoming packets are stored in case there is space
in the queue, otherwise the packets are discarded. In order to regulate the
output flow, leaky bucket transmits one packet from the queue in a fixed
time (e.g. at every clock tick). In the following figure we can notice the
main rationale of leaky bucket algorithm, for both the two approaches
(e.g. leaky bucket with water (a) and with packets (b)).
import java.util.Scanner;
public class p12
{
public static void main(String[] args) throws InterruptedException
{
Scanner in=new Scanner(System.in);
int n,incoming,outgoing,bs,s=0;
System.out.println("enter the bs,outgoing rate,inputs,incoming size");
bs=in.nextInt();
outgoing=in.nextInt();
n=in.nextInt();
incoming=in.nextInt();
while(n!=0)
{
System.out.println("incoming size is"+incoming);
if(incoming<=(bs-s))
{
s+=incoming;
System.out.println("bucket buffer size is"+s+"out of"+bs);
}
else
{
System.out.println("packet lost="+(incoming-(bs-s)));
s=bs;
System.out.println("bucket buffersize is"+s+"out of"+bs);
}
s-=outgoing;
System.out.println("after outgoing="+s+"packet left out of"+bs+"in
buffer");
n--;
Thread.sleep(3000);
}
in.close();
}
}
VIVA QUESTIONS
Ans: It is the exchange of data between two devices via some form of
transmission medium such as wire cable. The communicating system must be
part of a communication system made up of a combination of hardware and
software. The effectiveness of a data communication system depends on three
fundamental characteristics: delivery, accuracy and timeliness.
2. What is simplex?
3. What is half-duplex?
5. What is a network?
Ans: It provides a dedicated link between two devices. The entire capacity of
the link is reserved for transmission between the two devices e.g. when we
change the TV channels by remote control we establish a point to point
connection between remote control and TV control system.
Ans: In multipoint connection more than two specific devices share a single
link. Here the capacity of the channel is shared either separately or temporally.
9. What is a topology?
Ans: LAN- A local area network (LAN) is a privately owned and links the devices
in a single office, building or campus. It allows resources to be shared between
personal computers and work stations. MAN- A metropolitan-area network
(MAN) spreads over an entire city. It may be wholly owned and operated by a
private company, eg local telephone company. WAN – A wide area network
(WAN) provides long distance transmission of data, voice, image and video
information over large geographic areas that comprise a country, a continent
or even whole world.
Ans: It is a five layered model which provides guidelines for the development of
universally compatible networking protocols. The five layers are physical, data
link, network, transport and application.
14. Describe the functions of five layers?
Ans: Physical- It transmits raw bits over a medium. It provides mechanical and
electrical specification. Data link- It organizes bits into frames. It provides hop
to hop delivery. Network-It moves the packets from source to destination. It
provides internetworking. Transport-It provides reliable process to process
message delivery and error recovery. Application-It allows it access to network
resources.
Ans: Multiplexing is the process of dividing a link, the physical medium, into
logical channels for better efficiency. Here medium is not changed but it has
several channels instead of one.
Ans: Analog signals can have an infinite number of values in a range but digital
signal can have only a limited number of values.
Ans: The range of frequencies that a medium can pass is called bandwidth. It is
the difference between the highest and lowest frequencies that the medium
can satisfactorily pass.
Ans: Data rate ie. how fast we can send data depends upon i) Bandwidth
available ii) The levels of signals we can use iii) The quality of the channel (level
of noise)
Ans: For a noiseless channel, the Nyquist bit rate formula defines the
theoretical maximum bit rate Bitrate=2* Bandwidth*log2L Where Bandwidth is
the bandwidth of the channel L is the number of signal level used to represent
the data Bitrate is the bit rate in bits per second.
Ans: Shannon Capacity determines the theoretical highest data rate foe a noise
channel. Capacity= Bandwidth * log2 (1+SNR) Bandwidth is the bandwidth of
the channel.
SNR is the signal to noise ratio, it is the statistical ratio of the power of the
signal to the power of the noise. Capacity is the capacity of the channel in bits
per second
Ans: According to this theorem, the sampling rate must be at least 2 times the
highest frequency of the original signal.
Ans: In TDM digital signals from n devices are interleaved with one another,
forming a frame of data. Framing bits allow the TDM multiplexer to
synchronize properly.
Ans: The transmission media is broadly categorized into two types i) Guided
media(wired) i) Unguided media(wireless)
Ans: The media which provides a conduct from one device to another is called
a guided media. These include twisted pair cable, coaxial cable, and fiber-optic
cable.
Ans: Twisted pair cable consists of two insulated cupper wires twisted
together. It is used in telephone line for voice and data communications.
Coaxial cable has the following layers: a metallic rod-shaped inner conductor,
an insulator covering the rod, a metallic outer conductor (shield), an insulator
covering the shield, and a plastic cover. Coaxial cable can carry signals of higher
frequency ranges than twisted-pair cable. Coaxial cable is used in cable TV
networks and Ethernet LANs.Fiber-optic cables are composed of a glass or
plastic inner core surrounded by cladding, all encased in an outer jacket. Fiber-
optic cables carry data signals in the form of light. The signal is propagated
along the inner core by reflection. Its features are noise resistance, low
attenuation, and high bandwidth capabilities. It is used in backbone networks,
cable TV networks, and fast Ethernet networks.
Ans: There are three fundamental switching methods: circuit switching, packet
switching, and message switching. In circuit switching, a direct physical
connection between two devices is created by space division switches, time
division switches or both. In packet switching data is transmitted using a packet
switched network. Packet switched network is a network in which data are
transmitted in independent units called packets.
Ans: Data link layer is responsible for carrying packets from one hop (computer
or router) to the next. The duties of data link layer include packetizing,
addressing, error control, flow control, medium access control.
Ans: Errors can be categorized as a single-bit error or burst error. A single bit
error has one-bit error per data unit. A burst error has two or more bits errors
per data unit.
Ans: Redundancy is the concept of sending extra bits for use in error detection.
Three common redundancy methods are parity check, cyclic redundancy check
(CRC), and checksum.
Ans: The hamming code is an error correction method using redundant bits.
The number of bits is a function of the length of the data bits. In hamming code
for a data unit of m bits, we use the formula 2r >= m+r+1 to determine the
number of redundant bits needed. By rearranging the order of bit transmission
of the data units, the hamming code can correct burst errors.
Ans: It is the regulation of sender’s data rate so that the receiver buffer doesn’t
become overwhelmed.i.e. flow control refers to a set of procedures used to
restrict the amount of data that the sender can send before waiting for
acknowledgement.
Ans: In stop and wait ARQ, the sender sends a frame and waits for an
acknowledgement from the receiver before sending the next frame.
Ans: In Go-Back-N ARQ, multiple frames can be in transit at the same time. If
there is an error, retransmission begins with the last Unacknowledged frame
even if subsequent frames arrived correctly. Duplicate frames are discarded.
Ans: In Selective Repeat ARQ, multiple frames can be in transit at the same
time. If there is an error, only unacknowledged frame is retransmitted.
52. What do you mean by pipelining, is there any pipelining in error control?
Ans: The process in which a task is often begun before the previous task has
ended is called pipelining. There is no pipelining in stop and wait ARQ however
it does apply in Go-Back-N ARQ and Selective Repeat ARQ.
Ans: It is a bit oriented data link protocol designed to support both half duplex
and full duplex communication over point to point and multi point links. HDLC
is characterized by their station type, configuration and their response modes.
Ans: The point to point protocol was designed to provide a dedicated line for
users who need internet access via a telephone line or a cable TV connection.
Its connection goes through three phases: idle, establishing, authenticating,
networking and terminating. At data link layer it employs a version of HDLC.
Ans: Point to point protocol uses a stack of other protocol to use the link, to
authenticate the parties involved, and to carry the network layer data. Three
sets of protocols are defined: link control protocol, Authentication protocol,
and network control protocol.
Ans: The internet address (IP address) is 32bits that uniquely and universally
defines a host or router on the internet. The portion of the IP address that
identifies the network is called net-id. The portion of the IP address that
identifies the host or router on the network is called host-id.
Ans: Sub-netting divides one large network into several smaller ones. It adds an
intermediate level of hierarchy in IP addressing.
Ans: The advantages of fiber optics cable over twisted pair cable are Noise
resistance-As they use light so external noise is not a factor. Less signal
attenuation-fiber optics transmission distance is significantly greater than that
of other guided media. Higher bandwidth. It can support higher bandwidth.
Ans: The disadvantages of fiber optics cable over twisted pair cable are Cost-It
is expensive Installation/maintenance-Any roughness or cracking defuses light
and alters the signal Fragility-It is more fragile.
Ans: Radio wave propagation is dependent upon frequency. There are five
propagation type. i)surface propagation ii) Tropospheric propagation iii)
Lonospheric propagation iv) Line of sight propagation v) Space propagation
67. What are the factors for evaluating the suitability of the media?
Ans: The protocols used to determine who goes next on a multi-access channel
belong to a sublayer of the data link layer is called the multi-access
channel(MAC) sublayer. It is the bottom part of data link layer.
Ans: It is the method used to solve the channel allocation problem. It is used
for: i) ground based radio broadcasting ii) In a network in which uncoordinated
users are competing for the use of single channel. It is of two types: 1. Pure
aloha 2. Slotted aloha
Ans: It lets users transmit whenever they have data to send. Collision may
occur but due to feedback property sender can know the status of message.
Conflict occur when at one time more bits are transmitted. The assumptions
are: i) all frame size is same for all user. ii)collision occur when frames are
transmitted simultaneously iii) indefinite population of no of user.
iv)N=number of frames/frame time iv) it obeys poison’s distribution if N>1
there will be collision 0<1
Ans: In this method time is divided into discrete intervals, each interval
corresponding to one frame. It requires user to agree on slot boundaries. Here
data is not send at any time instead it wait for beginning of the next slot. Thus
pure ALOHA is turned into discrete one.
72. What do you mean by persistent CSMA (carrier sense multiple access)?
Ans: When a station has data to send, it first listens to the channel to see if
anyone else is transmitting at that moment. If channel is busy it waits until the
station becomes idle. When collision occurs it waits and then sends. It sends
frame with probability 1 when channel is idle.
Ans: Here if no one else is sending the station begins doing so itself. However,
if the channel is already in use, the station doesn’t continuously sense it rather
it waits for a random period of time and then repeats. It leads better channel
utilization but longer delay.
74. What do you mean by p persistent CSMA (carrier sense multiple access)?
Ans: It is high performance fiber optic token ring LAN running at 100Mbps over
distance up 1000 stations. FDDI access is limited by time. A FDDI cabling consist
of two fiber rings. i)one transmitting clockwise ii) one transmitting
counterclockwise
Ans: They divide large network into smaller components. They can relay frames
between two originally separated LANs. They provide security through
partitioning traffic. They operate on physical and data link layer of OSI model.
Ans: It is any device that is source of or destination for binary digital data. At
physical layer it can be a terminal computer. They generate or consume
information.
Ans: The list of protocols used by certain system, one protocol per layer is
called protocol stack.
Ans: The design issue of layer are • Addressing technique.ie source and
destination address • Types of communication • Error control • Order of
message. • Speed matching • Multiplexing and de-multiplexing.
Ans: The protocols defined in application layer are • TELNET • FTP • SMTP •
DNS
• TCP • UDP
Ans: In client server model, the client runs a program to request a service and
the server runs a program to provide the service. These two programs
communicate with each other. One server program can provide services to
many client programs.
95. What are the information that a computer attached to a TCP/IP internet
must possesses?
Ans: Domain Name System (DNS) is a client server application that identifies
each host on the internet with a unique user friendly name.
Ans: When a user logs into a local time-sharing system, it is called local login.
When a user wants to access an application program or utility located on a
remote machine, he or she performs remote login.
99. What is Network Virtual Terminal?
Ans: The TCP/IP protocol that supports electronic mail on the internet is called
Simple Mail Transfer Protocol. SMTP provides for mail exchange between users
on the same or different computer and supports Sending a single message to
one or more recipient Sending message that include text, voice, video, or
graphics. Sending message to users on network outside the internet.
Ans: It is the main protocol used to access data on the World Wide Web. the
protocol transfers data in the form of plain text, hypertext, audio, video and so
on. It is so called because its efficiency allows its use in a hypertext
environment where there are rapid jumps from one document to another.