0% found this document useful (0 votes)
9 views54 pages

Lab_Manual

The document outlines the Computer Networks Laboratory course (18CSL57) for the V Semester B.E at Sir M Visvesvaraya Institute of Technology, detailing its objectives, program outcomes, and specific outcomes. It includes a list of practical experiments, coding assignments, and guidelines for conducting practical examinations. The document also emphasizes the importance of network simulators and provides examples of various types of simulators used in the field.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
9 views54 pages

Lab_Manual

The document outlines the Computer Networks Laboratory course (18CSL57) for the V Semester B.E at Sir M Visvesvaraya Institute of Technology, detailing its objectives, program outcomes, and specific outcomes. It includes a list of practical experiments, coding assignments, and guidelines for conducting practical examinations. The document also emphasizes the importance of network simulators and provides examples of various types of simulators used in the field.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 54

SIR M VISVESVARAYA INSTITUTE OF TECHNOLOGY

(Affiliated to VTU, Recognized by AICTE and Accredited by NBA, NAAC


and an ISO 9001-2008 Certified Institution)
Bengaluru – 562157

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

COMPUTER NETRWORKS LABORATORY


CHOICE BASEDCREDITSYSTEM

18CSL57- V Semester B.E


(Academic Year 2020-21)

Name : _________________________________________________________

USN : ___________________________ Branch: _________________________

Semester : _______________________ Section: __________________________

Compiled and Prepared by: Under the Guidance of:


Ms. Savitha P, Mr. Elaiyaraja P Dr. G. C. Banu Prakash
Assistant Professor Professor. & Head
Dept. of CSE Dept. of CSE

Department Vision and Mission


VISION
To create a center for imparting quality technical education and conducting research to meet
the current and future challenges in the domain of computer science and engineering.
MISSION
 The Computer Science and Engineering department strives for excellence in teaching,
applying, promoting and imparting knowledge through comprehensive academic
programs.
 Train students to effectively apply the knowledge to solve real-world problems, thus
enhance their potential for life-long high-quality career and give them a competitive
advantage in the ever-changing and fast paced computing world.
 Prepare students to demonstrate a sense of societal and ethical responsibilities in their
professional endeavors.
 Creating amongst students and faculty a collaborative environment open to the free
exchange of ideas, where research, creativity, innovation and entrepreneurship can
flourish.
PROGRAM OUTCOMES

PO's PO Description
Engineering knowledge: Apply the knowledge of mathematics, science, engineering
PO1 fundamentals, and an engineering specialization to the solution of complex
engineering problems.
Problem analysis: Identify, formulate, review research literature, and analyze
PO2 complex engineering problems reaching substantiated conclusions using first
principles of mathematics, natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex engineering
problems and design system components or processes that meet the specified needs
PO3
with appropriate consideration for the public health and safety, and the cultural,
societal, and environmental considerations.
Conduct investigations of complex problems: Use research-based knowledge and
PO4 research methods including design of experiments, analysis and interpretation of
data, and synthesis of the information to provide valid conclusions.
Modern tool usage: Create, select, and apply appropriate techniques, resources, and
PO5 modern engineering and IT tools including prediction and modeling to complex
engineering activities with an understanding of the limitations.
The engineer and society: Apply reasoning informed by the contextual knowledge
PO6 to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to the professional engineering practice.
Environment and sustainability: Understand the impact of the professional
PO7 engineering solutions in societal and environmental contexts, and demonstrate the
knowledge of, and need for sustainable development.
Ethics: Apply ethical principles and commit to professional ethics and
PO8
responsibilities and norms of the engineering practice.
Individual and team work: Function effectively as an individual, and as a member
PO9
or leader in diverse teams, and in multidisciplinary settings.
Communication: Communicate effectively on complex engineering activities with
the engineering community and with society at large, such as, being able to
PO10
comprehend and write effective reports and design documentation, make effective
presentations, and give and receive clear instructions.
Project management and finance: Demonstrate knowledge and understanding of
the engineering and management principles and apply these to one’s own work, as a
PO11
member and leader in a team, to manage projects and in multidisciplinary
environments.
Life-long learning: Recognize the need for, and have the preparation and ability to
PO12 engage in independent and life-long learning in the broadest context of technological
change.

PROGRAM SPECIFIC OUTCOMES

PSO's PSO Description


An ability to design and analyze algorithms by applying theoretical concepts to build complex
PSO1 and computer- based systems in the domain of System Software, Computer Networks &
Security, Web technologies, Data Science and Analytics.
Be able to develop various software solutions by applying the techniques of Data Base
PSO2 Management, Complex Mathematical Models, Software Engineering practices and Machine
Learning with Artificial Intelligence.
SIR M VISVESVARAYA INSTITUTE OF TECHNOLOGY
(Affiliated to VTU, Recognized by AICTE and Accredited by NBA,
NAAC and an ISO 9001-2008 Certified Institution)
Bengaluru – 562157

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

CERTIFICATE
This is to certify that Mr/Ms. ______________________________________

bearing USN __________________________ has completed the

COMPUTER NETWORKS LABORATORY prescribed by Visvesvaraya

Technology University for Fifth Semester, academic year 20__ - 20__

Name and Signature of Staff

Signature of HOD
COMPUTER NETWORK LABORATORY
(Effective from the academic year 2018 -2019)
SEMESTER – V
Course Code 18CSL57 CIE Marks 40
Number of Contact Hours/Week 0:2:2 SEE Marks 60
Total Number of Lab Contact Hours 36 Exam Hours 03
Credits – 2
Course Learning Objectives: This course (18CSL57) will enable students to:
 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.
Descriptions (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.
 Installation procedure of the required software must be demonstrated, carried out in
groups and documented in the journal.
Programs List:
PART A

Implement three nodes point – to – point network with duplex links between them. Set the
1.
queue size, vary the bandwidth and find the number of packets dropped.

Implement transmission of ping messages/trace route over a network topology consisting of 6


2.
nodes and find the number of packets dropped due to congestion.
Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot congestion
3.
window for different source / destination.
Implement simple ESS and with transmitting nodes in wire-less LAN by simulation and
4.
determine the performance with respect to transmission of packets.
Implement and study the performance of GSM on NS2/NS3 (Using MAC layer) or
5.
equivalent environment.

Implement and study the performance of CDMA on NS2/NS3 (Using stack called Call net)
6.
or equivalent environment

PART B (Implement the following in Java)

7. Write a program for error detecting code using CRC-CCITT (16- bits).

8. Write a program to find the shortest path between vertices using bellman-ford algorithm.

9. 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.

10. Write a program on datagram socket for client/server to display the messages on client side,
typed at the server side.
11. Write a program for simple RSA algorithm to encrypt and decrypt the data.

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

Laboratory Outcomes: The student should be able to:


 Analyze and Compare various networking protocols.
 Demonstrate the working of different concepts of networking.
 Implement, analyze and evaluate networking protocols in NS2 / NS3 and JAVA programming
language
Conduct of Practical Examination:
 Experiment distribution
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
experiment 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
COMPUTER NETWORK LABORATORY 18CSL57

Introduction to Network Simulators

Network simulators implemented in software are valuable tools for researchers todevelop, test,
and diagnose network protocols. Simulation is economical because it can carry out experiments
without the actual hardware. It is flexible because it can, for example, simulate a link with any
bandwidth and propagation delay. Simulation results are easier to analyze than experimental
results because important information at critical points can be easily logged to help researchers
diagnose network protocols.
Network simulators, however, have their limitations. A complete network simulator needs to
simulate networking devices (e.g., hosts and routers) and application programs that generate
network traffic. It also needs to provide network utility programs to configure, monitor, and
gather statistics about a simulated network. Therefore, developing a complete network simulator
is a large effort. Due to limited development resources, traditional network simulators usually
have the following drawbacks:
• Simulation results are not as convincing as those produced by real hardware and software
equipment. In order to constrain their complexity and development cost, most network
simulators usually can only simulate real-life network protocol implementations with limited
details, and this may lead to incorrect results.
• These simulators are not extensible in the sense that they lack the standard UNIX POSIX
application programming interface (API). As such, existing or to-be-developed real-life
application programs cannot run normally to generate traffic for a simulated network.
Instead, they must be rewritten to use the internal API provided by the simulator (if there is any)
and be compiled with the simulator to form a single, big, and complex program.
To overcome these problems, Wang invented a kernel re-entering simulation methodology and
used it to implement the Harvard network simulator. Later on, Wang further improved the
methodology and used it to design and implement the NCTUns network simulator and emulator.
Different types of simulators
Some of the different types of simulators are as follows:-
 MIT's NETSIM
 NIST
 CPSIM
 INSANE
 NEST
 REAL
 NS
 OPNET
 NCTUns
 P
 GNS3
 WireShark

Department of Computer Science and Engineering, Sir MVIT Page | 1


COMPUTER NETWORK LABORATORY 18CSL57

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.

Source Code :

pa1.tcl

set ns [new Simulator]

set nf [open pa1.nam w]


$ns namtrace-all $nf

set tf [open pa1.tr w]


$ns trace-all $tf

proc finish {} {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam pa1.nam &
exit 0
}
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]

#$ns color 1 "red"


#$ns color 2 "blue"

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


$ns duplex-link $n1 $n2 50Mb 5ms DropTail
$ns duplex-link $n2 $n3 10Mb 1000ms DropTail

#$ns duplex-link $n0 $n2 color "green"

$ns queue-limit $n0 $n2 10


$ns queue-limit $n1 $n2 10

set udp0 [new Agent/UDP]


$ns attach-agent $n0 $udp0

Department of Computer Science and Engineering, Sir MVIT Page | 2


COMPUTER NETWORK LABORATORY 18CSL57

set cbr0 [new Application/Traffic/CBR]


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

set udp1 [new Agent/UDP]


$ns attach-agent $n1 $udp1

set cbr1 [new Application/Traffic/CBR]


$cbr1 attach-agent $udp1

set udp2 [new Agent/UDP]


$ns attach-agent $n2 $udp2

set cbr2 [new Application/Traffic/CBR]


$cbr2 attach-agent $udp2

set null0 [new Agent/Null]


$ns attach-agent $n3 $null0

$ns connect $udp0 $null0


$ns connect $udp1 $null0

$ns at 0.1 "$cbr0 start"


$ns at 0.2 "$cbr1 start"
$ns at 1.0 "finish"

$ns run
Source Code :

pa1.awk

BEGIN {
c=0;
}
{
if ($1=="d")
{
c++;
printf("%s\t%s\n",$5,$11);
}
}
END{
printf("The number of packet dropped= %d\n",c);
}

Department of Computer Science and Engineering, Sir MVIT Page | 3


COMPUTER NETWORK LABORATORY 18CSL57

Department of Computer Science and Engineering, Sir MVIT Page | 4


COMPUTER NETWORK LABORATORY 18CSL57

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.

Source Code:

pa2.tcl

set ns [ new Simulator ]


set nf [ open pa2.nam w ]
$ns namtrace-all $nf
set tf [ open pa2.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]
$n4 shape box
$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]


$ns attach-agent $n0 $p1
$p1 set packetSize_ 500000
$p1 set interval_ 0.0001
set p2 [new Agent/Ping]
$ns attach-agent $n1 $p2
set p3 [new Agent/Ping]
$ns attach-agent $n2 $p3
$p3 set packetSize_ 30000
$p3 set interval_ 0.00001
set p4 [new Agent/Ping]
$ns attach-agent $n3 $p4
set p5 [new Agent/Ping]
$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} {
$self instvar node_
puts "node [$node_ id] received answer from $from with round trip time $rtt msec"

Department of Computer Science and Engineering, Sir MVIT Page | 5


COMPUTER NETWORK LABORATORY 18CSL57

}
$ns connect $p1 $p5
$ns connect $p3 $p4
proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam pa2.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"
$ns at 0.2 "$p3 send"
$ns at 0.3 "$p3 send"
$ns at 0.4 "$p3 send"
$ns at 0.5 "$p3 send"

Department of Computer Science and Engineering, Sir MVIT Page | 6


COMPUTER NETWORK LABORATORY 18CSL57

$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

Source Code :

pa2.awk

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

Department of Computer Science and Engineering, Sir MVIT Page | 7


COMPUTER NETWORK LABORATORY 18CSL57

Department of Computer Science and Engineering, Sir MVIT Page | 8


COMPUTER NETWORK LABORATORY 18CSL57

Department of Computer Science and Engineering, Sir MVIT Page | 9


COMPUTER NETWORK LABORATORY 18CSL57

3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot congestion
window for different source / destination.

Source Code:

pa3.tcl

set ns [new Simulator]


set tf [open pa3.tr w]
$ns trace-all $tf
set nf [open pa3.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
$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]

Department of Computer Science and Engineering, Sir MVIT Page | 10


COMPUTER NETWORK LABORATORY 18CSL57

$ftp2 attach-agent $tcp2


$ftp2 set packetSize_ 600
$ftp2 set interval_ 0.0001
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_


$tcp2 trace cwnd_

proc finish { } {
global ns nf tf
$ns flush-trace
close $tf
close $nf
exec nam pa3.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

Source Code:

pa3.awk

BEGIN {
}
{
if($6=="cwnd_")
printf("%f\t%f\t\n",$1,$7);
}

Department of Computer Science and Engineering, Sir MVIT Page | 11


COMPUTER NETWORK LABORATORY 18CSL57

END{
}

Department of Computer Science and Engineering, Sir MVIT Page | 12


COMPUTER NETWORK LABORATORY 18CSL57

Department of Computer Science and Engineering, Sir MVIT Page | 13


COMPUTER NETWORK LABORATORY 18CSL57

4. Implement simple ESS and with transmitting nodes in wire-less LAN by simulation and
determine the performance with respect to transmission of packets.

Source Code:

pa4.tcl

set ns [new Simulator]


set tf [open pa4.tr w]
$ns trace-all $tf
set topo [new Topography]
$topo load_flatgrid 1000 1000
set nf [open pa4.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 \
-propType 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

Department of Computer Science and Engineering, Sir MVIT Page | 14


COMPUTER NETWORK LABORATORY 18CSL57

$ns at 0.1 "$n0 setdest 50 50 15"


$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 pa4.nam &
close $tf
exit 0
}
$ns at 250 "finish"
$ns run

Source Code:

pa4.awk

BEGIN{
count1=0
count2=0
pack1=0

Department of Computer Science and Engineering, Sir MVIT Page | 15


COMPUTER NETWORK LABORATORY 18CSL57

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)));
}

Department of Computer Science and Engineering, Sir MVIT Page | 16


COMPUTER NETWORK LABORATORY 18CSL57

Department of Computer Science and Engineering, Sir MVIT Page | 17


COMPUTER NETWORK LABORATORY 18CSL57

Department of Computer Science and Engineering, Sir MVIT Page | 18


COMPUTER NETWORK LABORATORY 18CSL57

5. Implement and study the performance of GSM on NS2/NS3 (Using MAC layer) or equivalent
environment.

Source Code:

pa5.tcl

# 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 $tf

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

Department of Computer Science and Engineering, Sir MVIT Page | 19


COMPUTER NETWORK LABORATORY 18CSL57

$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]

# 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]

Department of Computer Science and Engineering, Sir MVIT Page | 20


COMPUTER NETWORK LABORATORY 18CSL57

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

Department of Computer Science and Engineering, Sir MVIT Page | 21


COMPUTER NETWORK LABORATORY 18CSL57

Department of Computer Science and Engineering, Sir MVIT Page | 22


COMPUTER NETWORK LABORATORY 18CSL57

Department of Computer Science and Engineering, Sir MVIT Page | 23


COMPUTER NETWORK LABORATORY 18CSL57

6. Implement and study the performance of CDMA on NS2/NS3 (Using stack called Call net) or
equivalent environment.

Source Code:

pa6.tcl

# 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
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"

Department of Computer Science and Engineering, Sir MVIT Page | 24


COMPUTER NETWORK LABORATORY 18CSL57

}
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"
$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]

Department of Computer Science and Engineering, Sir MVIT Page | 25


COMPUTER NETWORK LABORATORY 18CSL57

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

Department of Computer Science and Engineering, Sir MVIT Page | 26


COMPUTER NETWORK LABORATORY 18CSL57

Department of Computer Science and Engineering, Sir MVIT Page | 27


COMPUTER NETWORK LABORATORY 18CSL57

PART - B

7. Write a program for error detecting code using CRC-CCITT (16- bits).

Cyclic Redundancy Check Code for Error – Detection


The cyclic Redundancy Check (CRC) id a technique for detecting errors in data transmission, but not for
correcting errors when they are detected.
CCITT- Consultative Committee for International Telegraphy and Telephone.

Algorithm:

A) For Computing CRC:


 The CRC Algorithm is based on polynomial arithmetic.
 Let the message that we have to send has k bits (denoted by M(x) in polynomial form having
degree (k-1)) the sender and the receiver are agreed upon a generator polynomial having r
bits (denoted by G(x) in polynomial form having degree (r-1)). The generator polynomial is
also called “Divisor”.
 Now, append (r-1) zero bits to the LSB side of the message M(x) so it will now contain (k+r-
1) bits and corresponds to the polynomial x (r-1) M (x).
 Divide the polynomial x(r-1) M (x) by Divisor, using modulo-2 subtraction (bit by bit XOR
operation). Add the remainder R(x) (called frame check sequence) to x (r-1) M (x), using
modulo -2 additions (bit by bit XOR operation). This is the message that will be transmitted
by the transmitter denoted by T(x).
B) For Error Detection:
 Suppose that a transmission error occurs, so that the received message at the receiver is T(x)
+E(x), instead of T(x). Each 1 bit in E(x) corresponds to a bit that has been inverted.
 The received message at the receiver end is divided by G(x), i.e. [T(x) + E(x) / G(x) ]. Since
T(x)/G(x) is 0, so the result is simply E(x)/G(x).
 If E(x)/G(x) =0 than there is no error in the received message, otherwise there is an error.
 The following type of errors can be detected using CRC:

Department of Computer Science and Engineering, Sir MVIT Page | 28


COMPUTER NETWORK LABORATORY 18CSL57

 If G(x) has more than one bit and the coefficient of x0 is 1, then all single bit errors
are detected.
 If G(x) is not divisible by x ( the coefficient of x0 is 1) , and t is the least positive
integer (0<t<n-1) such that G(x) divides x1 + 1, then all isolated double errors are
detected.
 If G(x) has a factor (x+1), then all odd numbered errors are detected.

Department of Computer Science and Engineering, Sir MVIT Page | 29


COMPUTER NETWORK LABORATORY 18CSL57

Source code:

import java.io.*;
class crc
{
public static void main(String[] args)
{
InputStreamReader isr=new InputStreamReader (System.in);
BufferedReader br=new BufferedReader(isr);
int[] message;
int[] gen;
int[] app_message;
int[] rem;
int[] trans_message;
int message_bits,gen_bits,total_bits;
System.out.println("\n Enter the no of bits in the message");
message_bits=Integer.parseInt(br.readLine());
message=new int[message_bits];
System.out.println("\n Enter the message bits");
for(int i=o;i<message_bits;i++)
message[i]=Integer.parseInt(br.readLine());
System.out.println("\n Enter the no of bits generated ");
gen_bits=Integer.parseInt(br.readLine());
gen=new int[gen_bits];
System.out.println("\n Enter the generated bits");
for(int i=o;i<gen_bits;i++);
{
gen[i]=Integer.parseInt(br.readLine());
}
total_bits=message_bits+gen_bits-1;
app_message=new int[total_bits];
rem=new int[total_bits];
trans_message=new int[total_bits];
for(int i=0;i<message.length;i++)
{
app_message[i]=message[i];
}
System.out.print("\n Message bits :");
for(int i=o;i<message_bits;i++)
{
System.out.print(message[i]);
}
System.out.print("\n Generated bits :");
for(int i=0;i<gen_bits;i++)
{
System.out.print(gen[i]);

Department of Computer Science and Engineering, Sir MVIT Page | 30


COMPUTER NETWORK LABORATORY 18CSL57

}
System.out.print("\n Appended message :");
for(int i=0;i<app_message.length;i++)
{
System.out.print(app_message[i]);
}
for(int j=0;j<app_message.length;j++)
{
rem[j]=app_message[j];
}
rem=computecrc(app_message.length;i++)
for(int i=0;i<app_message.length;i++)
{
trans_mesage[i]=(app_message[i]^rem[i]);
}
System.out.println("\n Transmitted message from the transmitter :");
for(int i=0;i<trans_message.length;i++)
{
System.out.print(trans_message[i]);
}
System.out.println("\n Message of"+total_bits+"bits received");
for(int i=0;i<trans_message.length;i++)
{
trans_messge[i]=Inter.parseInt(br.readLine());
}
System.out.println("\n Recevied message is :");
for(int i=0;i<trans_message.length;i++)
{
System.out.print(trans_message[i]);
}
for(int j=0;j<trans_message.length;j++)
{
rem[j]=trans_message[j];
}
rem=computercrc(trans_message,gen,rem);
for (int i=0;i<rem.length;i++)
{
if(rem[i]!=0)
{
System.out.println("\n There is error");
break;
}
if(i==rem.length-1)
{
System.out.println("\n There is no error");

Department of Computer Science and Engineering, Sir MVIT Page | 31


COMPUTER NETWORK LABORATORY 18CSL57

}
}

static int[] computecrc(int app_message[],int gen[],int rem[])


{
int current=0;
while(true)
{
for(int i=0;i<gen.length;i++)
{
rem[current+i]=(rem[current+i]^gen[i]);
}
while(rem[current]==0&&current!=rem.length-1)
{
current++;
}
if(rem.length-current)<gen.length)
{
break;
}
}
return rem;
}
}
}

Department of Computer Science and Engineering, Sir MVIT Page | 32


COMPUTER NETWORK LABORATORY 18CSL57

Out Put:

Enter the no of bits in the message : 4


Enter the message bits : 1 0 0 1
Enter the no of bits generated : 17
Enter the generated bits :
10001000000100001
Message bits: 1 0 0 1
Generated bits : 1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 1
Appended message : 1 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Transmitted message from transmitter : 1 0 0 1 1 0 0 1 0 0 0 1 0 0 1 0 1 0 0 1
Message of 20 bits received :
100 11001000100101001
There is no error

Enter the no of bits in the message : 4


Enter the message bits : 1 0 0 1
Enter the no of bits generated : 17
Enter the generated bits :
10001000000100001
Message bits: 1 0 0 1
Generated bits : 1 0 0 0 1 0 0 0 0 0 0 1 0 0 0 0 1
Appended message : 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Transmitted message from transmitter : 1 0 0 1 1 0 0 1 0 0 0 1 0 0 0 1 0 1 0 0 1
Message of 20 bits received :
10011001010100101010
There is an error

Department of Computer Science and Engineering, Sir MVIT Page | 33


COMPUTER NETWORK LABORATORY 18CSL57

8. Write a program to find the shortest path between vertices using bellman-ford algorithm.

Bell man ford algorithm is a procedure used to find all shortest path in a graph from one source to all
other nodes. The algorithm was introduced by American mathematicians Richard Bellman and
Lester ford. Computes shortest from a single source vertex to all of the other vertices in a weighted
diagraph.

Source Code:

import java.io.*;
import java.util.*;
import java.io.DataInputStream;
class Edge
{
int source;
int dest;
int weight;
}
class Bellman
{
public static void BellmanFord(Edge edges[], int edgecount, int nodecount, int source)
{
int infinity=50000;
int i, j;
int distance[]=new int[nodecount];
for(i=0; i&lt;nodecount; i++)
distance[i]=infinity;
distance[source]=0;
for(i=0; i&lt;nodecount; i++)
{
boolean somethingchanged=false;
for(j=0; j&lt;edgecount; j++)
{
if(distance[edges[j].source]!=infinity)
{
int new_distance=distance[edges[j].source]+edges[j].weight;
if(new_distance&lt;distance[edges[j].dest])
{
distance[edges[j].dest]=new_distance;
somethingchanged=true;

Department of Computer Science and Engineering, Sir MVIT Page | 34


COMPUTER NETWORK LABORATORY 18CSL57

}
}
}
if(!somethingchanged)
break;
}
for(i=0; i&lt;edgecount; ++i)
{
if(distance[edges[i].dest]&gt;distance[edges[i].source]+edges[i].weight)
System.out.println(&quot;Negative edge weight cycles detected!!!&quot;);
}
for(i=0; i&lt;nodecount; ++i)
System.out.println(&quot;The shortest distance between nodes &quot;+source+&quot; &amp;
&quot;+i+&quot; is &quot;+distance[i]);
}
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
Edge edges[]=new Edge[10];
for( int i=0; i&lt;10; i++)
{
edges[i]=new Edge();
System.out.print(&quot;Enter source number [&quot;+i+&quot;] : &quot;);
edges[i].source=in.nextInt();
System.out.print(&quot;Enter destination number [&quot;+i+&quot;] : &quot;);
edges[i].dest=in.nextInt();
System.out.print(&quot;Enter weight number [&quot;+i+&quot;] : &quot;);
edges[i].weight=in.nextInt();
System.out.println();
}
BellmanFord(edges, 10, 5, 4);
}
}

Department of Computer Science and Engineering, Sir MVIT Page | 35


COMPUTER NETWORK LABORATORY 18CSL57

Out Put:

Enter the number of vertices : 4


Enter the adjacency matrix:
0 5 999 999
5 0 2 4
999 2 0 1
999 4 1 0
Enter source of vertex: 1
Distance of source 1 to 1 is 0
Distance of source 1 to 2 is 5
Distance of source 1 to 3 is 7
Distance of source 1 to 4 is 8

Enter the number of vertices : 6


Enter the adjacency matrix:
0 10 3 999 999 999
999 0 999 -3 2 999
999 999 0 3 999 999
999 999 999 0 4 1
999 -1 999 999 0 999
999 999 999 999 4 0
Enter source of vertex: 1
Distance of source 1 to 1 is 0
Distance of source 1 to 2 is 9
Distance of source 1 to 3 is 3
Distance of source 1 to 4 is 6
Distance of source 1 to 5 is 10
Distance of source 1 to 6 is 7

Department of Computer Science and Engineering, Sir MVIT Page | 36


COMPUTER NETWORK LABORATORY 18CSL57

9. 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.

A socket is an endpoint of a two-way communication link between two programs running on the
network. Socket is bound to a port number so that the TCP layer can identify the application that data
is destinedto be sent. Java provides a set of classes, defined in a package called java.net, to enable the
rapiddevelopment of network applications.

The steps for creating a server program in TCP/IP are:


1. Open the Server Socket:
ServerSocket server = new ServerSocket( PORT );

2. Wait for the Client Request:


Socket client = server.accept(); // bind with the port no

3. Create I/O streams for communicating to the client


InputStream istream = sock.getInputStream( );
BufferedReader fileRead =new BufferedReader(new InputStreamReader(istream));

4. Perform communication with client


Receive from client: String fname = fileRead.readLine( );
Send to client: pwrite.println(str);

5. Close socket:
client.close();

The steps for creating a client program in TCP/IP are:

1. Create a Socket Object:


Socket client = new Socket(server, port_id);

2. Create I/O streams for communicating with the server.


is = new DataInputStream(client.getInputStream());
os = new DataOutputStream(client.getOutputStream());

3. Perform I/O or communication with the server:


Receive data from the server: String line = is.readLine();
Send data to the server: os.writeBytes(“Hello\n”);

4. Close the socket when done:


client.close();

Department of Computer Science and Engineering, Sir MVIT Page | 37


COMPUTER NETWORK LABORATORY 18CSL57

Source Code:

import java.net.*;
import java.io.*;
public class contentclient
{
public static void main( String args[ ] ) throws Exception
{
Socket sock = new Socket( "127.0.0.1", 4000);
System.out.print("Enter the file name");
BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
String fname = keyRead.readLine();
OutputStream ostream = sock.getOutputStream( );
PrintWriter pwrite = new PrintWriter(ostream, true);
pwrite.println(fname);
InputStream istream = sock.getInputStream();
BufferedReader socketRead = new BufferedReader(new InputStreamReader(istream));
String str;
while((str = socketRead.readLine()) != null)
{
System.out.println(str);
}
pwrite.close(); socketRead.close(); keyRead.close();
}
}

Source Code:
import java.net.*;
import java.io.*;
public class contentserver
{
public static void main(String args[]) throws Exception
{
ServerSocket sersock = new ServerSocket(4000);
System.out.println("Server ready for connection");
Socket sock = sersock.accept();
System.out.println("Connection is successful and wating for chatting");
InputStream istream = sock.getInputStream( );
BufferedReader fileRead =new BufferedReader(new InputStreamReader(istream));
String fname = fileRead.readLine( );
BufferedReader contentRead = new BufferedReader(new FileReader(fname) );
OutputStream ostream = sock.getOutputStream( );
PrintWriter pwrite = new PrintWriter(ostream, true);
String str;
while((str = contentRead.readLine()) != null)

Department of Computer Science and Engineering, Sir MVIT Page | 38


COMPUTER NETWORK LABORATORY 18CSL57

{
pwrite.println(str);
}
sock.close();
sersock.close();
pwrite.close();
fileRead.close();
contentRead.close();
}
}

Out Put:

Computer Network lab

Department of Computer Science and Engineering, Sir MVIT Page | 39


COMPUTER NETWORK LABORATORY 18CSL57

10. Write a program on datagram socket for client/server to display the messages on client side,
typed at the server side

Source Code:

Client:
import java.io.*;
import java.net.*;
public class udpc
{
public static void main(string[] args)
{
DatagramSocket skt;
try
{
skt=new DatagramSocket();
String msg=”udp”;
Byte[] b= msg.getBytes();
InetAddress host=InetAddress.getByName(“127.0.0.1”);
int serverSocket=6788;
DatagramPacket request=new DatagramPacket(b,b.length,host,serverSocket);
skt.send(request);
Byte[] buffer=new byte[1000];
DatagramPacket reply=new DatagramPacket(buffer,buffer.length);
skt.receive(reply);
System.out.println(“Client received :” + new String(reply.getData()));
skt.close();
}
Catch(Exception ex)
{}
}
}

Department of Computer Science and Engineering, Sir MVIT Page | 40


COMPUTER NETWORK LABORATORY 18CSL57

Server:
import java.io.*;
import java.net.*;
public class udps
{
public static void main(string[] args)
{
DatagramSocket Skt=null;
try
{
Skt=new DatagramSocket(6788);
Byte[] buffer= new byte(1000);
While(true)
{
DatagramPacket request=new DatagramPacket(buffer,buffer.length);
Skt.receive(request);
String[] message=(new string(request.getData())).split(“ “);
Byte[] sendMsg=(message[1]+”Network Laboratory”).getByte();
DatagramPacket
reply=newDatagramPacket(sendMsg,sendMsg.length,requ
est.getAddress(),request.getport());
Skt.send(reply);
System.out.println(“Client received :” + new String(reply.getData()));
Skt.close();
}
Catch(Exception ex)
{}
}
}

Out Put:
Server ready for communication
Connection successful and waiting for chatting
Enter file name:
Sample.txt
Hello
World

Department of Computer Science and Engineering, Sir MVIT Page | 41


COMPUTER NETWORK LABORATORY 18CSL57

11. Write a program for simple RSA algorithm to encrypt and decrypt the data.

RSA is an example of public key cryptography. It was developed by Rivest, Shamir and Adelman. The
RSA algorithm can be used for both public key encryption and digital signatures. Its security is based on
the difficulty of factoring large integers.

The RSA algorithm’s efficiency requires a fast method for performing the modular exponentiation
operation. A less efficient, conventional method includes raising a number (the input) to a power (the
secret or public key of the algorithm, denoted e and d, respectively) and taking the remainder of the
division with N. A straight- forward implementation performs these two steps of the operation
sequentially: first, raise it to the power and second, apply modulo. The RSA algorithm comprises of
three steps, which are depicted below:

Key generation algorithm

1. Generate two large random primes, p and q, of approximately equal size such that their product
n=p*q
2. Compute n= p*q and Euler’s totient function (@) phi(n) = (p-1)(q-1)
3. Choose an integer e, 1< e < phi, such that gcd(e, phi)=1
4. Compute the secret exponent d, 1< d <phi , such that e*d ≡1(mod phi)
5. The public key is (e,n) and the private key is (d,n). The values of p, q and phi should also be kept
secret.

Encryption

Sender A does the following:

1. Using the public key(e,n)


2. Represents the plaintext message as a positive integer M
3. Computes the cipher text C= M^e mod n.
4. Sends the cipher text C to B (Receiver)

Decryption

Recipient B does the following:

1. Uses his private key (d,n) to compute M=C^d mod n


2. Extracts the plaintext from the integer representative m.

Department of Computer Science and Engineering, Sir MVIT Page | 42


COMPUTER NETWORK LABORATORY 18CSL57

Source Code:

import java.io.DataInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
public class RSA12
{
private BigInteger p;
private BigInteger q;
private BigInteger N;
private BigInteger phi;
private BigInteger e;
private BigInteger d;
private int bitlength = 1024;
private Random r;
public RSA12()
{
r = new Random();
p = BigInteger.probablePrime(bitlength, r);
q = BigInteger.probablePrime(bitlength, r);
N = p.multiply(q);
phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e = BigInteger.probablePrime(bitlength / 2, r);
while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0)
{
e.add(BigInteger.ONE);
}
d = e.modInverse(phi);
}

public RSA12(BigInteger e, BigInteger d, BigInteger N)


{
this.e = e;
this.d = d;
this.N = N;
}

public static void main(String[] args) throws IOException


{
RSA12 rsa = new RSA12();
DataInputStream in = new DataInputStream(System.in);
String teststring;
System.out.println("Enter the plain text:");
teststring = in.readLine();

Department of Computer Science and Engineering, Sir MVIT Page | 43


COMPUTER NETWORK LABORATORY 18CSL57

System.out.println("Encrypting String: " + teststring);


System.out.println("String in Bytes: "+ bytesToString(teststring.getBytes()));
byte[] encrypted = rsa.encrypt(teststring.getBytes());
byte[] decrypted = rsa.decrypt(encrypted);
System.out.println("Decrypting Bytes: " + bytesToString(decrypted));
System.out.println("Decrypted String: " + new String(decrypted));
}

private static String bytesToString(byte[] encrypted)


{
String test = "";
for (byte b : encrypted)
{
test += Byte.toString(b);
}
return test;
}

public byte[] encrypt(byte[] message)


{
return (new BigInteger(message)).modPow(e, N).toByteArray();
}

public byte[] decrypt(byte[] message)


{
return (new BigInteger(message)).modPow(d, N).toByteArray();
}
}

Out Put:

Enter the plain text :


hello
Encrypting string : hello
String in bytes : 1 0 4 1 0 1 1 0 8 1 0 8 1 1 1
Encrypted string : CB@a83b8a
Decrypting string : 1 0 4 1 0 1 1 0 8 1 0 8 1 1 1
Decrypted string : hello

Department of Computer Science and Engineering, Sir MVIT Page | 44


COMPUTER NETWORK LABORATORY 18CSL57

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

What is congestion?
A state occurring in network layer when the message traffic is so heavy that it slows down network
response time.
Effects of Congestion

 As delay increases, performance decreases.


 If delay increases, retransmission occurs, making situation worse.

Traffic shaping or policing: To control the amount and rate of traffic is called Traffic shaping or
policing. Traffic shaping term is used when the traffic leaves a network. Policing term is used when the
data enters the network. Two techniques can shape or police the traffic leaky bucket and token bucket.

Congestion control algorithms

 Leaky Bucket Algorithm

Let us consider an example to understand


Imagine a bucket with a small hole in the bottom. No matter at what rate water enters the bucket, the
outflow is at constant rate. When the bucket is full with water additional water entering spills over the
sides and is lost.

Similarly, each network interface contains a leaky bucket and the following steps are involved in leaky
bucket algorithm:

1. When host wants to send packet, packet is thrown into the bucket.
2. The bucket leaks at a constant rate, meaning the network interface transmits packets at a
constant rate.
3. Bursty traffic is converted to a uniform traffic by the leaky bucket.
4. In practice the bucket is a finite queue that outputs at a finite rate.

Department of Computer Science and Engineering, Sir MVIT Page | 45


COMPUTER NETWORK LABORATORY 18CSL57

Source Code:

importjava.util.*;
public class leaky
{
public static void main(String[] args)
{
Scanner my = new Scanner(System.in);
intno_groups,bucket_size;
System.out.print("\n Enter the bucket size : \t");
bucket_size = my.nextInt();
System.out.print("\n Enter the no of groups : \t");
no_groups = my.nextInt();
intno_packets[] = new int[no_groups];
intin_bw[] = new int[no_groups];
intout_bw,reqd_bw=0,tot_packets=0;
for(inti=0;i<no_groups;i++)
{
System.out.print("\n Enter the no of packets for group " + (i+1) + "\t");
no_packets[i] = my.nextInt();
System.out.print("\n Enter the input bandwidth for the group " + (i+1) + "\t");
in_bw[i] = my.nextInt();
if((tot_packets+no_packets[i])<=bucket_size)
{
tot_packets += no_packets[i];
}
else
{
do
{
System.out.println(" Bucket Overflow ");
System.out.println(" Enter value less than " + (bucket_size-tot_packets));
no_packets[i] = my.nextInt();
}while((tot_packets+no_packets[i])>bucket_size);
tot_packets += no_packets[i];
}
reqd_bw += (no_packets[i]*in_bw[i]);
}
System.out.println("\nThe total required bandwidth is " + reqd_bw);
System.out.println("Enter the output bandwidth ");
out_bw = my.nextInt();
int temp=reqd_bw;
intrem_pkts = tot_packets;
while((out_bw<=temp)&&(rem_pkts>0))
{
System.out.println("Data Sent \n" + (--rem_pkts) + " packets remaining");

Department of Computer Science and Engineering, Sir MVIT Page | 46


COMPUTER NETWORK LABORATORY 18CSL57

System.out.println("Remaining Bandwidth " + (temp -= out_bw));


if((out_bw>temp)&&(rem_pkts>0))
System.out.println(rem_pkts + " packet(s) discarded due to insufficient bandwidth");
}
}
}

Out Put:

Enter bucket size : 20


Enter number of groups :2
Enter number of packets of group 1:2
Enter input bandwidth for group 1:2
Enter number of packets of group 2 :3
Enter input bandwidth for group 2 : 3
Total required bandwidth :13
Enter the output bandwidth:2
Data sent
4 packets remaining
Remaining bandwidth:11
Data sent
3 packets remaining
Remaining bandwidth : 9
Data sent
2 packets remaining
Remaining bandwidth :7
Data sent
1 packets remaining
Remaining bandwidth :5
Data sent
0 packets remaining
Remaining bandwidth :3

Department of Computer Science and Engineering, Sir MVIT Page | 47


COMPUTER NETWORK LABORATORY 18CSL57

Viva Questions:
1. What are functions of different layers?
2. Differentiate between TCP/IP Layers and OSI Layers
3. Why header is required?
4. What is the use of adding header and trailer to frames?
5. What is encapsulation?
6. Why fragmentation requires?
7. What is MTU?
8. Which layer imposes MTU?
9. Differentiate between flow control and congestion control.
10. Differentiate between Point-to-Point Connection and End-to-End connections.
11. What are protocols running in different layers?
12. What is Protocol Stack?
13. Differentiate between TCP and UDP.
14. Differentiate between Connectionless and connection oriented connection.
15. Why frame sorting is required?
16. What is meant by subnet?
17. What is meant by Gateway?
18. What is an IP address?
19. What is MAC address?
20. Why IP address is required when we have MAC address?
21. What is meant by port?
22. What are ephemerical port number and well known port numbers?
23. What is a socket?
24. What are the parameters of socket()?
25. Describe bind(), listen(), accept(), connect(), send() and recv().
26. What are system calls? Mention few of them.
27. What is meant by file descriptor?
28. What is meant by traffic shaping?
29. How do you classify congestion control algorithms?
30. How do you implement Leaky bucket?
31. How do you generate busty traffic?
32. What is the polynomial used in CRC-CCITT?
33. . What are the other error detection algorithms?
34. What are Routing algorithms?
35. How do you classify routing algorithms? Give examples for each.
36. What are drawbacks in distance vector algorithm?
37. How routers update distances to each of its neighbor?
38. How do you overcome count to infinity problem?
39. What is cryptography?

Department of Computer Science and Engineering, Sir MVIT Page | 48


COMPUTER NETWORK LABORATORY 18CSL57

40. How do you classify cryptographic algorithms?


41. What is public key?
42. What is private key?
43. What are key cipher text and plaintext?
44. What is simulation?
45. What are advantages of simulation?
46. Differentiate between Simulation and Emulation.
47. What is meant by router?
48. What is meant by bridge?
49. What is meant by switch?
50. What is meant by hub?
51. Differentiate between route, bridge, switch and hub.
52. What is ping and telnet?
53. What is FTP?
54. What is collision?
55. How do you generate multiple traffics across different sender-receiver pairs?
56. What is meant by mobile host?
57. Name few other Network simulators
58. Differentiate between logical and physical address.
59. Which address gets affected if a system moves from one place to anotherplace?
60. What is ICMP? What are uses of ICMP? Name few.
61. Which layer implements security for data?
62. What is connectionless and connection oriented protocol?
63. What is Congestion window?
64. What is flow control?

Department of Computer Science and Engineering, Sir MVIT Page | 49

You might also like