You are on page 1of 57

MITE 062

VISVESVARAYA TECHNOLOGICAL UNIVERSITY

Jnana Sangam, Belgaum-590018

COMPUTER NETWORKS LABORATORY


(15CSL57)

MANGALORE INSTITUTE OF TECHNOLOGY AND ENGINEERING


(An ISO 9001:2008 Certified Institution)

DEPARTMENT OF COMPUTER SCIENCE & ENGINEERING


Badaga Mijar, Moodbidri – 574225, Karnataka
Computer Network Laboratory 15CSL57

COMPUTER NETWORK LABORATORY


[As per Choice Based Credit System (CBCS) scheme]
(Effective from the academic year 2017 -2018)
SEMESTER – V
Subject Code 15CSL57 IA Marks 20

Number of Lecture Hours/Week 01I + 02P Exam Marks 80

Total Number of Lecture Hours 40 Exam Hours 03

Course Outcome

Course Outcome Cognitive Class POs


Level Sessions
CO1 Analyze and Compare various networking An,Ap 13 PO1-2h,
PO2-2h
protocols (Exp No. 9,10,1,2) PO3-1h,
PO4-3h,
PO5-2h
PO12-1h,
PSO2-2h
CO2 Demonstrate the working of different concepts U,Ap 13 PO3-3h, PO2-
3h,
of networking (Exp No. 7,8,11,12) PO3-2h
PO4-2h,
PO12-1h,
PSO2-2h
CO3 Implement, analyze and evaluate networking U,An 13 PO1-3h, PO2-
3h,
protocols in NS2 / NS3 (Exp No. 3,4,5,6) PO3-1h
PO4-3h,
PO12-1h,
PSO2-2h

Cognitive Level : R-Remember, U-Understand, Ap-Apply, An-Analyze, E-Evaluate, C-Create

Dept of CSE, MITE, Moodabidri Page 1


Computer Network Laboratory 15CSL57

SYLLABUS

PART A

1. Implement three nodes point – to – point network with duplex links between them. Set the queue size,
vary the bandwidth and find the number of packets dropped.
2. Implement transmission of ping messages/trace route over a network topology consisting of 6 nodes and
find the number of packets dropped due to congestion.
3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot congestion window for
different source / destination.
4. Implement simple ESS and with transmitting nodes in wire-less LAN by simulation and determine the
performance with respect to transmission of packets.
5. Implement and study the performance of GSM on NS2/NS3 (Using MAC layer) or equivalent
environment.
6. Implement and study the performance of CDMA on NS2/NS3 (Using stack called Call net) or equivalent
environment.

PART B

Implement the following in Java:

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. Implement the above program using as
message queues or FIFOs as IPC channels.
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.

STEPS FOR EXECUTION OF PROGRAMS


1. Open the terminal
2. Move to the directory /home/mite/Desktop/ns-allinone-2.35/ns-2.35
cd /home/mite/Desktop/ns-allinone-2.35/ns-2.35
3. Create a directory with your USN
mkdir USN
4. Change directory to USN
cd USN
5. Create files using gedit editor.
 gedit program1.tcl
6. command to execute the program
 ns program1.tcl

Dept of CSE, MITE, Moodabidri Page 2


Computer Network Laboratory 15CSL57

PROGRAM-1
TITLE

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.

AIM

analyzing the traffic between the nodes using different bandwidth ,propagation delay and queue size
of point to point duplex link and its effects on packet transmission.

DESCRIPTION

Ns2(network simulator2) is used for this experiment, in which point to point duplex link is created between
the node with varying queuing capacity of node. Bandwidth, propagation delay of a point to point link and
queuing capacity of a node is very important to minimize the affect on packet transmission. Ns2 simulated
data traffic analyzed by setting the different bandwidth, propagation delay and queuing capacity of a link
and corresponding its affect on packet transmission is noted. Awk script is used for analyzing the out.tr trace
log file generated upon executing the ns2 simulation script for determining the packet drops.

INPUT

Different Bandwidth, propagation delay & queuing capacity of node of duplex link awk scripts for
analyzing the out.tr trace log file for determining the number of packet drop.

EXPECTED OUTPUT

(a) generate the out.tr trace log file and out.nam network animation file.
(b) number of packet drop

PROGRAM (1)

# This script is created by NSG2 beta1

# <http://wushoupong.googlepages.com/nsg>

#===================================

# Simulation parameters setup

#===================================

set val(stop) 30.0 ;# time of simulation end

#===================================

Dept of CSE, MITE, Moodabidri Page 3


Computer Network Laboratory 15CSL57

# Initialization

#===================================

#Create a ns simulator

set ns [new Simulator]

#Open the NS trace file

set tracefile [open out.tr w]

$ns trace-all $tracefile

#Open the NAM trace file

set namfile [open out.nam w]

$ns namtrace-all $namfile

#===================================

# Nodes Definition

#===================================

#Create 3 nodes

set n0 [$ns node]

set n1 [$ns node]

set n2 [$ns node]


#===================================

# Links Definition

#===================================

#Createlinks between nodes

$ns duplex-link $n0 $n1 100.0Mb 10ms DropTail

$ns queue-limit $n0 $n1 02

$ns duplex-link $n1 $n2 1.0Mb 50ms DropTail

$ns queue-limit $n1 $n2 02

Dept of CSE, MITE, Moodabidri Page 4


Computer Network Laboratory 15CSL57

#Give node position (for NAM)

$ns duplex-link-op $n0 $n1 orient right

$ns duplex-link-op $n1 $n2 orient right

#===================================

# Agents Definition

#===================================

#Setup a TCP connection

set tcp0 [new Agent/TCP]

$ns attach-agent $n0 $tcp0

set sink1 [new Agent/TCPSink]

$ns attach-agent $n2 $sink1

$ns connect $tcp0 $sink1

$tcp0 set packetSize_ 1500

#===================================

# Applications Definition

#===================================

#Setup a FTP Application over TCP connection

set ftp0 [new Application/FTP]

$ftp0 attach-agent $tcp0

$ns at 1.0 "$ftp0 start"

$ns at 20.0 "$ftp0 stop"

#===================================

# Termination

#===================================
#Define a 'finish' procedure

proc finish {} {

Dept of CSE, MITE, Moodabidri Page 5


Computer Network Laboratory 15CSL57

global ns tracefile namfile

$ns flush-trace

close $tracefile

close $namfile

exec nam out.nam &

exit 0

$ns at $val(stop) "$ns nam-end-wireless $val(stop)"

$ns at $val(stop) "finish"

$ns at $val(stop) "puts \"done\" ; $ns halt"

$ns run

RESULT

Illustration 1: AWK Script for counting number of packets drop

Drawing 1: NAM Output

Dept of CSE, MITE, Moodabidri Page 6


Computer Network Laboratory 15CSL57

PROGRAM -2
TITLE

(a)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.

AIM
to understand the working principle of ICMP Ping message and deeper insights into the congestion scenario
caused by successive ping message among nodes.

DESCRIPTION
Ping is the one of popular mechanism for internet control messaging protocol. Ping message is used
for determining the reach ability and aliveness of the remote/ destination machine in a network. In this
experiment, network simulator2 is used for creating network topology consisting of 6 nodes interconnected
by point to point duplex link. Nodes on the created topology issues ping command to the other nodes in the
network and generate traffic. Node upon receiving the ping message will respond by sending a ping reply
message to the requesting node and generate return traffic in the network. Successive ping message by
different nodes generates huge traffic on the network and cause packet drop scenario.

INPUT

 ping message from nodes.


 awk scripts for analyzing the out.tr trace log file for determining the number of packet drop.

EXPECTED OUTPUT

1. Ping response from corresponding nodes.


2. Generate the out.tr trace log file and out.nam network animation file.
3. Number of packet drop

PROGRAM (2)
#Create a simulator object
set ns [new Simulator]
#Open a trace file

set nf [open exp4.nam w]

$ns namtrace-all $nf

set nd [open exp4.tr w]

Dept of CSE, MITE, Moodabidri Page 7


Computer Network Laboratory 15CSL57

$ns trace-all $nd

$ns color 1 Red

$ns color 2 Green

#Define a 'finish' procedure

proc finish {} {

global ns nf nd

$ns flush-trace

close $nf

close $nd

exec nam exp4.nam &

exit 0

#Create six nodes

set n0 [$ns node]

set n1 [$ns node]

set n2 [$ns node]

set n3 [$ns node]

set n4 [$ns node]

set n5 [$ns node]

#Connect the nodes with two links

$ns duplex-link $n0 $n1 0.1Mb 10ms DropTail

$ns duplex-link $n1 $n2 0.1Mb 10ms DropTail

$ns duplex-link $n2 $n3 0.1Mb 10ms DropTail

$ns duplex-link $n3 $n4 0.1Mb 10ms DropTail

$ns duplex-link $n4 $n5 0.1Mb 10ms DropTail

Dept of CSE, MITE, Moodabidri Page 8


Computer Network Laboratory 15CSL57

$ns duplex-link-op $n0 $n1 orient right

$ns duplex-link-op $n1 $n2 orient right

$ns duplex-link-op $n2 $n3 orient down

$ns duplex-link-op $n3 $n4 orient left

$ns duplex-link-op $n4 $n5 orient left

#Define a 'recv' function for the class 'Agent/Ping'

Agent/Ping instproc recv {from rtt} {

$self instvar node_

puts "node [$node_ id] received ping answer from \

#$from with round-trip-time $rtt ms."

#Create two ping agents and attach them to the nodes n0 and n2

set p0 [new Agent/Ping]

$ns attach-agent $n0 $p0

$p0 set fid_ 1

set p1 [new Agent/Ping]

$ns attach-agent $n5 $p1

$p1 set fid_ 2

#Connect the two agents

$ns connect $p0 $p1

#Schedule events

$ns at 0.2 "$p0 send"

$ns at 0.4 "$p1 send"

Dept of CSE, MITE, Moodabidri Page 9


Computer Network Laboratory 15CSL57

$ns at 0.6 "$p0 send"

$ns at 0.8 "$p1 send"

$ns at 1.0 "finish"

#Run the simulation

$ns run

RESULT

Dept of CSE, MITE, Moodabidri Page 10


Computer Network Laboratory 15CSL57

PROGRAM-3
TITLE

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

AIM

To understand the working principle of Ethernet LAN and congestion scenarios using multiple data traffic.
DESCRIPTION
 Ethernet LAN denoted by IEEE 802.3 is one of the popular computer networking technology. In this
experiment, ns2 simulator is used for creating Ethernet LAN and set the two different data traffic
between pair of nodes using TCP as transport layer agent. Simulated data traffic between pair of
nodes is analyzed for determining the packet drop due to congestion in the network. Congestion
window for each TCP traffic is plotted on graph using xgraph tool.

INPUT

 Ethernet LAN Bandwidth, propagation delay, Queue Type and channel type
 two TCP traffic between pair of nodes
 initial Congestion window for both the traffic.
 awk scripts for analyzing the out.tr trace log file for determining the number of packet drop.

EXPECTED OUTPUT

 generate the out.tr trace log file, winfile0, winfile1 and out.nam network animation file.
 Generate Windowsize_file0, WindowSize_file1 holding congestion window size of both the traffic at
different instance of time.
 number of packet drop.
 Xgraph plotted graph of depicting the congestion window of both the traffic.

PROGRAM (3)
set ns [new Simulator]

#Use colors to differentiate the traffics

$ns color 1 Blue

$ns color 2 Red

#Open trace and NAM trace file

set ntrace [open prog7.tr w]

$ns trace-all $ntrace

Dept of CSE, MITE, Moodabidri Page 11


Computer Network Laboratory 15CSL57

set namfile [open prog7.nam w]

$ns namtrace-all $namfile

#Use some flat file to create congestion graph windows

set winFile0 [open WinFile0 w]

set winFile1 [open WinFile1 w]

#Finish Procedure

proc Finish {} {

#Dump all trace data and Close the files

global ns ntrace namfile

$ns flush-trace

close $ntrace

close $namfile

#Execute the NAM animation file

exec nam prog7.nam &

#Plot the Congestion Window graph using xgraph

exec xgraph WinFile0 WinFile1 &

exit 0

#Plot Window Procedure

proc PlotWindow {tcpSource file} {

global ns

set time 0.1

set now [$ns now]

set cwnd [$tcpSource set cwnd_]

puts $file "$now $cwnd"

Dept of CSE, MITE, Moodabidri Page 12


Computer Network Laboratory 15CSL57

$ns at [expr $now+$time] "PlotWindow $tcpSource $file"

#Create 6 nodes

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

set n($i) [$ns node]

#Create duplex links between the nodes

$ns duplex-link $n(0) $n(2) 2Mb 10ms DropTail

$ns duplex-link $n(1) $n(2) 2Mb 10ms DropTail

$ns duplex-link $n(2) $n(3) 0.6Mb 100ms DropTail

#Nodes n(3) , n(4) and n(5) are considered in a LAN

set lan [$ns newLan "$n(3) $n(4) $n(5)" 0.5Mb 40ms LL Queue/DropTail MAC/802_3 Channel]

#Orientation to the nodes

$ns duplex-link-op $n(0) $n(2) orient right-down

$ns duplex-link-op $n(1) $n(2) orient right-up

$ns duplex-link-op $n(2) $n(3) orient right

#Setup queue between n(2) and n(3) and monitor the queue

$ns queue-limit $n(2) $n(3) 20

$ns duplex-link-op $n(2) $n(3) queuePos 0.5

#Set error model on link n(2) to n(3)

set loss_module [new ErrorModel]

$loss_module ranvar [new RandomVariable/Uniform]

$loss_module drop-target [new Agent/Null]

$ns lossmodel $loss_module $n(2) $n(3)

#Set up the TCP connection between n(0) and n(4)

Dept of CSE, MITE, Moodabidri Page 13


Computer Network Laboratory 15CSL57

set tcp0 [new Agent/TCP/Newreno]

$tcp0 set fid_ 1

$tcp0 set window_ 8000

$tcp0 set packetSize_ 552

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

set sink0 [new Agent/TCPSink/DelAck]

$ns attach-agent $n(4) $sink0

$ns connect $tcp0 $sink0

#Apply FTP Application over TCP

set ftp0 [new Application/FTP]

$ftp0 attach-agent $tcp0

$ftp0 set type_ FTP

#Set up another TCP connection between n(5) and n(1)

set tcp1 [new Agent/TCP/Newreno]

$tcp1 set fid_ 2

$tcp1 set window_ 8000

$tcp1 set packetSize_ 552

$ns attach-agent $n(5) $tcp1

set sink1 [new Agent/TCPSink/DelAck]

$ns attach-agent $n(1) $sink1

$ns connect $tcp1 $sink1

#Apply FTP application over TCP

set ftp1 [new Application/FTP]

$ftp1 attach-agent $tcp1

$ftp1 set type_ FTP

Dept of CSE, MITE, Moodabidri Page 14


Computer Network Laboratory 15CSL57

#Schedule Events

$ns at 0.1 "$ftp0 start"

$ns at 0.1 "PlotWindow $tcp0 $winFile0"

$ns at 0.5 "$ftp1 start"

$ns at 0.5 "PlotWindow $tcp1 $winFile1"

$ns at 25.0 "$ftp0 stop"

$ns at 25.1 "$ftp1 stop"

$ns at 25.2 "Finish"

#Run the simulation

$ns run

RESULT

Dept of CSE, MITE, Moodabidri Page 15


Computer Network Laboratory 15CSL57

PROGRAM-4
TITLE

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

AIM

To understand how Extended Service Set is created and works by providing services to nodes in wirlesess
LAN and analyzing the wireless traffic for determining packet drops.

DESCRIPTION
In this experiment, network simulator2 is used to create a IEEE 802.11 Wireless LAN consisting of mobile
nodes and Extended Service set. An extended service set (ESS) is one or more interconnected basic service
sets (BSSs) and their associated LANs. Each BSS consists of a single access point (AP) together with all
wireless client devices (stations, also called STAs) creating a local or enterprise 802.11 wireless LAN
(WLAN). Wireless mobile nodes

INPUT

 two TCP traffic between pair of nodes


 awk scripts for analyzing the out.tr trace log file for determining the number of packet drop.

EXPECTED OUTPUT

 generate the out.tr trace log file, and


 generate the out.nam network animation file depicting the IEEE 802.3 Wireless LAN.

#===================================
# Simulation parameters setup
#===================================
set val(chan) Channel/WirelessChannel ;# channel type
set val(prop) Propagation/TwoRayGround ;# radio-propagation model
set val(netif) Phy/WirelessPhy ;# network interface type
set val(mac) Mac/802_11 ;# MAC type
set val(ifq) Queue/DropTail/PriQueue ;# interface queue type
set val(ll) LL ;# link layer type
set val(ant) Antenna/OmniAntenna ;# antenna model
set val(ifqlen) 50 ;# max packet in ifq
set val(nn) 5 ;# number of mobilenodes
set val(rp) AODV ;# routing protocol
set val(x) 939 ;# X dimension of topography
set val(y) 558 ;# Y dimension of topography
Dept of CSE, MITE, Moodabidri Page 16
Computer Network Laboratory 15CSL57

set val(stop) 90.0 ;# time of simulation end

#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]

#Setup topography object


set topo [new Topography]
$topo load_flatgrid $val(x) $val(y)
create-god $val(nn)

#Open the NS trace file


set tracefile [open out.tr w]
$ns trace-all $tracefile

#Open the NAM trace file


set namfile [open out.nam w]
$ns namtrace-all $namfile
$ns namtrace-all-wireless $namfile $val(x) $val(y)
set chan [new $val(chan)];#Create wireless channel

#===================================
# Mobile node parameter setup
#===================================
$ns node-config -adhocRouting $val(rp) \
-llType $val(ll) \
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
-channel $chan \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace ON \
-movementTrace ON

#===================================
# Nodes Definition
#===================================
#Create 5 nodes
set n0 [$ns node]
$n0 set X_ 261
$n0 set Y_ 85
$n0 set Z_ 0.0
$ns initial_node_pos $n0 20

Dept of CSE, MITE, Moodabidri Page 17


Computer Network Laboratory 15CSL57

set n1 [$ns node]


$n1 set X_ 388
$n1 set Y_ 288
$n1 set Z_ 0.0
$ns initial_node_pos $n1 20
set n2 [$ns node]
$n2 set X_ 544
$n2 set Y_ 458
$n2 set Z_ 0.0
$ns initial_node_pos $n2 20
set n3 [$ns node]
$n3 set X_ 699
$n3 set Y_ 284
$n3 set Z_ 0.0
$ns initial_node_pos $n3 20
set n4 [$ns node]
$n4 set X_ 839
$n4 set Y_ 105
$n4 set Z_ 0.0
$ns initial_node_pos $n4 20

#===================================
# Agents Definition
#===================================
#Setup a TCP connection
set tcp0 [new Agent/TCP]
$ns attach-agent $n0 $tcp0
set sink1 [new Agent/TCPSink]
$ns attach-agent $n4 $sink1
$ns connect $tcp0 $sink1
$tcp0 set packetSize_ 1500

#===================================
# Applications Definition
#===================================
#Setup a FTP Application over TCP connection
set ftp0 [new Application/FTP]
$ftp0 attach-agent $tcp0
$ns at 1.0 "$ftp0 start"
$ns at 5.0 "$n0 setdest 700 151 10"
$ns at 100.0 "$ftp0 stop"

#===================================
# Termination
#===================================
#Define a 'finish' procedure
proc finish {} {
global ns tracefile namfile

Dept of CSE, MITE, Moodabidri Page 18


Computer Network Laboratory 15CSL57

$ns flush-trace
close $tracefile
close $namfile
exec nam out.nam &
exit 0
}
for {set i 0} {$i < $val(nn) } { incr i } {
$ns at $val(stop) "\$n$i reset"
}
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
$ns run

RESULT

Dept of CSE, MITE, Moodabidri Page 19


Computer Network Laboratory 15CSL57

PROGRAM-5
TITLE

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

AIM

To understand the GSM TDMA Mac layer functionality under different traffic scenario and mobility of
nodes.

DESCRIPTION
GSM stands for Global System for Mobile Communication. It is a digital cellular technology used for
transmitting mobile voice and data services. GSM uses narrowband Time Division Multiple Access (TDMA)
for providing voice and text based services over mobile phone networks. Radio spectrum being a limited
resource that is consumed and divided among all the users, GSM devised a combination of TDMA/FDMA
as the method to divide the bandwidth among the users. In this process, the FDMA part divides the
frequency of the total 25 MHz bandwidth into 124 carrier frequencies of 200 kHz bandwidth. Each BS is
assigned with one or multiple frequencies, and each of this frequency is divided into eight timeslots using a
TDMA scheme. Each of these slots are used for both transmission as well as reception of data. These slots
are separated by time so that a mobile unit doesn’t transmit and receive data at the same time. In this
experiment, network simulator2 is used for simulating GSM network using TDMA as a MAC layer for
nodes and performance of data communication is analyzed under different scenario.

INPUT

 Two TCP traffic between pair of nodes


 Awk scripts for analyzing the out.tr trace log file for determining the number of packet drop.

EXPECTED OUTPUT

(a) Generate the out.tr trace log file, and


(b) Generate the out.nam network animation file depicting the GSM Nework by creating base station
node and mobile nodes.

#===================================
# Simulation parameters setup
#===================================
set val(chan) Channel/WirelessChannel ;# channel type
set val(prop) Propagation/TwoRayGround ;# radio-propagation model

Dept of CSE, MITE, Moodabidri Page 20


Computer Network Laboratory 15CSL57

set val(netif) Phy/WirelessPhy ;# network interface type


set val(mac) Mac/Tdma ;# MAC type
set val(ifq) Queue/DropTail/PriQueue ;# interface queue type
set val(ll) LL ;# link layer type
set val(ant) Antenna/OmniAntenna ;# antenna model
set val(ifqlen) 50 ;# max packet in ifq
set val(nn) 7 ;# number of mobilenodes
set val(rp) AODV ;# routing protocol
set val(x) 1478 ;# X dimension of topography
set val(y) 100 ;# Y dimension of topography
set val(stop) 90.0 ;# time of simulation end

#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]

#Setup topography object


set topo [new Topography]
$topo load_flatgrid $val(x) $val(y)
create-god $val(nn)

#Open the NS trace file


set tracefile [open out.tr w]
$ns trace-all $tracefile

#Open the NAM trace file


set namfile [open out.nam w]
$ns namtrace-all $namfile
$ns namtrace-all-wireless $namfile $val(x) $val(y)
set chan [new $val(chan)];#Create wireless channel

#===================================
# Mobile node parameter setup
#===================================
Phy/WirelessPhy set freq_ 2.472e6
$ns node-config -adhocRouting $val(rp) \
-llType $val(ll) \
-macType $val(mac) \
-ifqType $val(ifq) \
-ifqLen $val(ifqlen) \
-antType $val(ant) \
-propType $val(prop) \
-phyType $val(netif) \
-channel $chan \
-topoInstance $topo \
-agentTrace ON \
-routerTrace ON \
-macTrace ON \

Dept of CSE, MITE, Moodabidri Page 21


Computer Network Laboratory 15CSL57

-movementTrace ON

#===================================
# Nodes Definition
#===================================
#Create 7 nodes
set n0 [$ns node]
$n0 set X_ 271
$n0 set Y_ 58
$n0 set Z_ 0.0
$ns initial_node_pos $n0 20
set n1 [$ns node]
$n1 set X_ 458
$n1 set Y_ 214
$n1 set Z_ 0.0
$ns initial_node_pos $n1 20
set n2 [$ns node]
$n2 set X_ 666
$n2 set Y_ 344
$n2 set Z_ 0.0
$ns initial_node_pos $n2 20
set n3 [$ns node]
$n3 set X_ 877
$n3 set Y_ 229
$n3 set Z_ 0.0
$ns initial_node_pos $n3 20
set n4 [$ns node]
$n4 set X_ 1103
$n4 set Y_ 150
$n4 set Z_ 0.0
$ns initial_node_pos $n4 20
Phy/WirelessPhy set freq_ 2.472e9
$ns node-config -phyType $val(netif)
set n5 [$ns node]
$n5 set X_ 616
$n5 set Y_ 55
$n5 set Z_ 0.0
$ns initial_node_pos $n5 20
set n6 [$ns node]
$n6 set X_ 722
$n6 set Y_ 55
$n6 set Z_ 0.0
$ns initial_node_pos $n6 20

#===================================
# Agents Definition
#===================================
#Setup a TCP connection
set tcp1 [new Agent/TCP]
$ns attach-agent $n5 $tcp1

Dept of CSE, MITE, Moodabidri Page 22


Computer Network Laboratory 15CSL57

set sink3 [new Agent/TCPSink]


$ns attach-agent $n6 $sink3
$ns connect $tcp1 $sink3
$tcp1 set packetSize_ 1500

#Setup a TCP connection


set tcp5 [new Agent/TCP]
$ns attach-agent $n0 $tcp5
set sink6 [new Agent/TCPSink]
$ns attach-agent $n4 $sink6
$ns connect $tcp5 $sink6
$tcp5 set packetSize_ 1500

#===================================
# Applications Definition
#===================================
#Setup a FTP Application over TCP connection
set ftp1 [new Application/FTP]
$ftp1 attach-agent $tcp5
$ns at 1.0 "$ftp1 start"
$ns at 80.0 "$ftp1 stop"

#Setup a FTP Application over TCP connection


set ftp2 [new Application/FTP]
$ftp2 attach-agent $tcp1
$ns at 1.0 "$ftp2 start"
$ns at 80.0 "$ftp2 stop"

#===================================
# Termination
#===================================
#Define a 'finish' procedure
proc finish {} {
global ns tracefile namfile
$ns flush-trace
close $tracefile
close $namfile
exec nam out.nam &
exit 0
}
for {set i 0} {$i < $val(nn) } { incr i } {
$ns at $val(stop) "\$n$i reset"
}
$ns at $val(stop) "$ns nam-end-wireless $val(stop)"
$ns at $val(stop) "finish"
$ns at $val(stop) "puts \"done\" ; $ns halt"
$ns run

Dept of CSE, MITE, Moodabidri Page 23


Computer Network Laboratory 15CSL57

RESULT

Dept of CSE, MITE, Moodabidri Page 24


Computer Network Laboratory 15CSL57

PROGRAM-6
TITLE

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

AIM
To understand the CDMA Mac layer functionality under different traffic scenario and mobility of nodes.

DESCRIPTION

LTE is the latest high- speed cellular transmission network.LTE is a 4G technology with download speeds that run the gamut
from 3 to 28 Mbps worldwide.4G LTE is one of several competing 4G standards along with Ultra Mobile Broadband (UMB) and
WiMax (IEEE 802.16).Ns3 is the best choice among network simulator for simulating LTE framework. We provide customized
NS3 LTE Simulation Projects based on customer Requirements.

INPUT
 Two TCP traffic between pair of nodes
 Awk scripts for analyzing the out.tr trace log file for determining the number of packet drop.

EXPECTED OUTPUT

(a) Generate the out.tr trace log file, and


(b) Generate the out.nam network animation file depicting the GSM Nework by creating base station
node and mobile nodes.

PROGRAM – 6A.PL

#include "ns3/core
-
module.h"
#include "ns3/network
-
module.h"
#include "ns3/mobility
-
module.h"
#include "ns3/lte
-
module.h"
#include "ns3/config
-
store
-
Dept of CSE, MITE, Moodabidri Page 25
Computer Network Laboratory 15CSL57

module.h"
using namespace ns3;
int main (int argc, char *argv[])
{
CommandLine cmd;
cmd.Parse (argc, argv)
;
ConfigStore inputConfig;
inputConfig.ConfigureDefaults ();
cmd.Parse (argc, argv);
Ptr<LteHelper> lteHelper = CreateObject<LteHelper> ();
lteHelper
-
>SetAttribute ("PathlossModel", StringValue
("ns3::FriisSpectrumPropagationLossModel"));
NodeContainer enb
Nodes;
NodeContainer ueNodes;
enbNodes.Create (1);
ueNodes.Create (3);
MobilityHelper mobility;
mobility.SetMobilityModel ("ns3::ConstantPositionMobilityModel");
mobility.Install (enbNodes);
mobility.SetMobilityModel
("ns3::ConstantPositionMobilityModel");
mobility.Install (ueNodes);
NetDeviceContainer enbDevs;
NetDeviceContainer ueDevs;
enbDevs = lteHelper
-
>InstallEnbDevice (enbNodes);
ueDevs = lteHelper
-
>InstallUeDevice (ueNodes);
lteHelper
-
>Attach (ueDevs, enbDevs.
Get (0));
enum EpsBearer::Qci q = EpsBearer::GBR_CONV_VOICE;
EpsBearer bearer (q);

Dept of CSE, MITE, Moodabidri Page 26


Computer Network Laboratory 15CSL57

lteHelper
-
>ActivateDataRadioBearer (ueDevs, bearer);
Simulator::Stop (Seconds (0.5));
lteHelper
-
>EnablePhyTraces ();
lteHelper
-
>EnableMacTraces ();
lteHelper
-
>EnableRlcTrac
es ();
double distance_temp [] = { 1000,1000,1000};
std::vector<double> userDistance;
userDistance.assign (distance_temp, distance_temp + 3);
for (int i = 0; i < 3; i++)
{
Ptr<ConstantPositionMobilityModel> mm = ueNodes.Get
(i)
-
>GetObject<
ConstantPositionMobilityModel> (); mm
-
>SetPosition (Vector (userDistance[i], 0.0, 0.0)); }
Simulator::Run ();
Simulator::Destroy ();
return 0;
}

RESULT

Dept of CSE, MITE, Moodabidri Page 27


Computer Network Laboratory 15CSL57

PART B
STEPS FOR EXECUTION OF PROGRAMS

1. Start Eclipse
2. Create a new java project
3. Create a new java class

Dept of CSE, MITE, Moodabidri Page 28


Computer Network Laboratory 15CSL57

4. Run the program

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

AIM
To detect the error at receiver side

DESCRIPTION
CRC is an error detection mechanism. CRC is based on binary division. In this a sequence of
redundant bits, called CRC remainder is appended to the end of a data unit so that the resulting data unit
becomes exactly divisible by a second predetermined binary number. At its destination, the incoming data
unit is divided by the same number. If at this step there is no reminder, the data unit is assumed to be intact
and therefore accepted. A remainder indicates that the data unit has been changed in transit and therefore
must be rejected.
The generalized technique can be explained as follows.
If a k bit message is to be transmitted, the transmitter generates an r-bit sequence, known as Frame
Check Sequence (FCS) so that the (k +r) bits are actually being transmitted. Now this r-bit FCS is generated
by dividing the original number, appended by r zeros, by a predetermined number. This number, which is
(r+1) bit in length, can also be considered as the coefficients of a polynomial, called Generator Polynomial.
The remainder of this division process generates the r-bit FCS. On receiving the packet, the receiver divides
the (k+r) bit frame by the same predetermined number and if it produces no remainder, it can be assumed
that no error has occurred during the transmission.

Dept of CSE, MITE, Moodabidri Page 29


Computer Network Laboratory 15CSL57

INPUT
a) Enter the Data word
b) Enter the position where error has to be inserted

EXPECTED OUTPUT

Dept of CSE, MITE, Moodabidri Page 30


Computer Network Laboratory 15CSL57

a) Print the Generating Polynomial


b) Print the modified Bits
c) Print the checksum
d) Print the Final Code word
e) Print the error occurred data

PROGRAM: CRC
package crcsender;

import java.util.Scanner;

public class CRCSender {

public static void main(String[] args) {


// TODO code application logic here
Scanner scan = new Scanner(System.in);
String msg, crc, encoded = " ";
System.out.println("Enter the message");
msg = scan.next();
System.out.println("Enter the crc generator polynomial");
crc = scan.next();
int m = msg.length(), n = crc.length();
encoded+= msg ;

//************************ Logic to generate the codeword ***********************//

char[] generatorPolyArray = crc.toCharArray();

for(int i=1; i<=n-1;i++)encoded+='0';


System.out.println("E:"+encoded);
char[] encodedArray = encoded.toCharArray();
for(int i=0;i<=encodedArray.length-n;){
for(int j=0;j<n;j++)
encodedArray[i+j] = ((encodedArray[i+j]==generatorPolyArray[j])?'0':'1');
for(;i<encoded.length() && encodedArray[i]!='1';i++);
}
String finalmsg = new String(encodedArray);
System.out.println("MES : "+msg+finalmsg.substring(finalmsg.length()-n+1));

String newmsg = msg+finalmsg.substring(finalmsg.length()-n+1);

//***************************Logic to test the CRC at receiver *********************//


System.out.println("Enter (1. To test for the CRC, 2. To induce error and Test");
int i = scan.nextInt();

char[] toTryArray = newmsg.toCharArray();

//************************ Choice 1: Check for Validity 2:Induce error and cross check
***************//

Dept of CSE, MITE, Moodabidri Page 31


Computer Network Laboratory 15CSL57

if(i==1){
for(int k =0;k<toTryArray.length-crc.length();){
for(int z=0;z<crc.length();z++)
toTryArray[k+z] = ((toTryArray[k+z]==generatorPolyArray[z])?'0':'1');
for(;k<toTryArray.length && toTryArray[k]!='1';k++);
}
String ouptput = new String(toTryArray);
if(ouptput.equals("0000000"))
System.out.println("No Error");
else
System.out.println("Error");
}
else
{
System.out.println("The CodeWord is "+new String(toTryArray));
System.out.println("Enter the bit you want to alter starting from 0 ");
int pos = scan.nextInt();
System.out.println("Enter the bit you want to change");
int value = scan.nextInt();
toTryArray[pos] = (char)value;

for(int k =0;k<toTryArray.length-crc.length();){
for(int z=0;z<crc.length();z++)
toTryArray[k+z] = ((toTryArray[k+z]==generatorPolyArray[z])?'0':'1');
for(;k<toTryArray.length && toTryArray[k]!='1';k++);
}
String ouptput = new String(toTryArray);
if(ouptput.equals("0000000"))
System.out.println("No Error");
else
System.out.println("Error");

}
}

Dept of CSE, MITE, Moodabidri Page 32


Computer Network Laboratory 15CSL57

RESULT

Dept of CSE, MITE, Moodabidri Page 33


Computer Network Laboratory 15CSL57

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

AIM
To find the shortest path to all the different nodes from a source.

DESCRIPTION
The Bellman–Ford algorithm is an algorithm that computes shortest paths from a single source vertex to all of the
other vertices in a weighted digraph.[1] It is slower than Dijkstra's algorithm for the same problem, but more versatile,
as it is capable of handling graphs in which some of the edge weights are negative numbers.

Negative edge weights are found in various applications of graphs, hence the usefulness of this algorithm.[3] If a graph
contains a "negative cycle" (i.e. a cycle whose edges sum to a negative value) that is reachable from the source, then
there is no cheapest path: any path that has a point on the negative cycle can be made cheaper by one
more walk around the negative cycle. In such a case, the Bellman–Ford algorithm can detect negative cycles and
report their existence

1) This step initializes distances from source to all vertices as infinite and distance to source itself as 0. Create an
array dist[] of size |V| with all values as infinite except dist[src] where src is source vertex.

2) This step calculates shortest distances. Do following |V|-1 times where |V| is the number of vertices in given
graph.

Do following for each edge u-v

If dist[v] > dist[u] + weight of edge uv, then update dist[v]


dist[v] = dist[u] + weight of edge uv

3) This step reports if there is a negative weight cycle in graph.


Do following for each edge u-v
If dist[v] > dista) Do [u] + weight of edge uv, then “Graph contains negative weight cycle”
The idea of step 3 is, step 2 guarantees shortest distances if graph doesn’t contain negative weight cycle. If we
iterate through all edges one more time and get a shorter path for any vertex, then there is a negative weight
cycle.

INPUT
a) Enter the number of nodes
b) Enter the adjacent matrix

EXPECTED OUTPUT
a) Print the routing table with shortest distance from each source to sink.

PROGRAM: BELLMAN FORD

package bellmanford;
import java.util.Scanner;

Dept of CSE, MITE, Moodabidri Page 34


Computer Network Laboratory 15CSL57

public class BellmanFord

{
private int distances[];

private int numberofvertices;

public static final int MAX_VALUE = 999;


public BellmanFord(int numberofvertices)

{
this.numberofvertices = numberofvertices;

distances = new int[numberofvertices + 1];

}
public void BellmanFordEvaluation(int source, int adjacencymatrix[][])

for (int node = 1; node <= numberofvertices; node++)

distances[node] = MAX_VALUE;

}
distances[source] = 0;

for (int node = 1; node <= numberofvertices - 1; node++)

{
for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++)

{
for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++)

{
if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE)

if (distances[destinationnode] > distances[sourcenode]

+ adjacencymatrix[sourcenode][destinationnode])

distances[destinationnode] = distances[sourcenode]

+ adjacencymatrix[sourcenode][destinationnode];

Dept of CSE, MITE, Moodabidri Page 35


Computer Network Laboratory 15CSL57

}
for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++)
{

for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++)

if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE)

if (distances[destinationnode] > distances[sourcenode]

+ adjacencymatrix[sourcenode][destinationnode])

System.out.println("The Graph contains negative egde cycle");

for (int vertex = 1; vertex <= numberofvertices; vertex++)

System.out.println("distance of source " + source + " to "

+ vertex + " is " + distances[vertex]);

public static void main(String... arg)

int numberofvertices = 0;

int source;

Dept of CSE, MITE, Moodabidri Page 36


Computer Network Laboratory 15CSL57

Scanner scanner = new Scanner(System.in);


System.out.println("Enter the number of vertices");
numberofvertices = scanner.nextInt();
int adjacencymatrix[][] = new int[numberofvertices + 1][numberofvertices + 1];
System.out.println("Enter the adjacency matrix");
for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++)
{
for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++)
{

adjacencymatrix[sourcenode][destinationnode] = scanner.nextInt();

if (sourcenode == destinationnode)

adjacencymatrix[sourcenode][destinationnode] = 0;

continue;

if (adjacencymatrix[sourcenode][destinationnode] == 0)

adjacencymatrix[sourcenode][destinationnode] = MAX_VALUE;

System.out.println("Enter the source vertex");


source = scanner.nextInt();
BellmanFord bellmanford = new BellmanFord(numberofvertices);

bellmanford.BellmanFordEvaluation(source, adjacencymatrix);
scanner.close();

RESULT

Dept of CSE, MITE, Moodabidri Page 37


Computer Network Laboratory 15CSL57

Dept of CSE, MITE, Moodabidri Page 38


Computer Network Laboratory 15CSL57

PROGRAM-3
TITLE

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

AIM
To demonstrate client server {Request and Reply} concept by using socket programming

DESCRIPTION
Unix sockets is just like two way FIFO's. All data communication will take place through the socket's
interface, instead of through the file interface. Although unix socket's are a special file in the file system(just
like FIFO's), there's usage of socket(), bind(), recv(),etc and not open(), read().
When programming with socket's, usually there's creation of server and client programs. The server
will sit listening for incoming connections from clients and handling. This is similar to the situation that
exists with internet sockets but with fine differences.
For instance, when describing which unix socket that has to be used(i.e the path to the special file
that is the socket). The structure “struct sockaddr_un” has the following fields:
struct sockaddr_un
{
unsigned short sa_family; // Address family,AF_XXXX
char sa_data; // 14 bytes of protocol address
};
This is the structure you will be passing to the bind() function, which associates a socket descriptor(a
file descriptor) with a certain file(the name for which is in the sun_path field). The structure “struct
sockaddr_in” is used when we need IP address and Port number to be binded to the Sockets. It has following
fields:
struct sockaddr_in
{
short int sin_family; // Address family
unsigned short int sin_port; // Port number
struct in_addr sin_addr; // Internet address
unsigned char sin_zero[8] // Same size as struct sockaddr
};

Dept of CSE, MITE, Moodabidri Page 39


Computer Network Laboratory 15CSL57

// Internet adress
struct in_addr
{
unsigned long s_addr; // 32 bits or 4 bytes long
};
ii. BACKGROUND REQUIRED:
1. UNIX File I/O system calls
2. UNIX IPC system calls
3. UNIX socket programming

iii. THEORETICAL CONCEPTS:


Most interprocess communication uses the client server model. These terms refer to the two
processes which will be communication with each other. One of the two processes , the client , connects to
the other process, the server, typiceally to make a request for information. A good analogy is a person who
makes a phone call to another person.
Notice that the client needs to know of the existence of and the address of the server, but the server
does not need to know the adresss of(or even the existence of) the client prior to the connection being
established. Notice also that once a connection is established, both sides can send and receive information.
The system calls for establishing a connection are somewhat different for the client and the server,
but both involve the basic construct of a socket. A socket is one end of an interprocess communication
channel. The two processes each establish their own socket.
The steps involved in establishing a socket on the client side are as follows-
1. Create a socket with the socket() system call .
2. Connect the socket to the address of the server using the connect() system call.
3. Send and receive data. There are a number of ways to do this, but the simplest is to use the read()
and write() systen calls.
The steps involved in establishing a socket on the server side are as follows-
1. Create a socket with the socket() system call.
2. Bind the socket to an address using the bind() system call. For a server socket on the internet, an
address consists of a port number on the host machine.
3. Listen for connections with the listen() system call.
4. Acept a connection with the accept() system call. This call typically blocks until a client connects
with the server.
5. Send and receive the data.
Dept of CSE, MITE, Moodabidri Page 40
Computer Network Laboratory 15CSL57

Socket Types:
When a socket is created, the program has to specify the address domain and the socket type. Two
processes can communicate with each other only if their sockets are of the same type and in the same
domain, in which two processes running on any two hosts on the Internet communicate. Each of these has
it's own adress format.
The address of a socket in the Unix domain is a character string which is basically an entry in the file
system.
The address of a socket in the Internet domain consists of the Internet address of the host machine
(every computer on the Internet has a unique 32 bit address, often reffered to as it's IP address). In addition ,
each socket needs a port number on that host. Port numbers are 16 bit unsigned integers. The lower numbers
are reserved in Unix for standard services. For eg, the port number for the FTP server is 21.
There are two widely used socket types, stream sockets , and datgram sockets. Stream sockets treat
communications as a continuous stream of characters, while datagram sockets have to read entire messages
at once. Each uses it's own communications protocol. Stream sockets use TCP , which is a reliable , stream
oriented protocol, and datagram sockets use UDP, which is unreliable and message oriented.
The primary socket calls are as follows:-
1. socket() - Create a new socket and return it's descriptor.
2. bind() - Associate a socket with a port and address .
3. Listen() -Establish a queue for connection requests.
4. Accept()- Accepts a connection request.
5. Connect()- Initiate a connection to a remote host.
6. Recv() - Receive data from a socket descriptor.
7. Send() - Send data to a socket descriptor.
8. Close() - “one-way” close of a socket descriptor,
The other system calls used are as follows:-
1. gethostbyname- given a hostname , returns a structure which specifies it's DNS name(s) and IP
address(es).
2. getservbyname – given service name and protocol , returns a structure which specifies its name(s) and
its port address.
The socket utility functions are as follows:-
1. htons/ntohl- convert short/long from host byte order to network byte order.
2. inet_ntoa/inet_addr- converts 32 bit IP address (network byte order to/from a dotted decimal string)
The header files used in order are:-
Dept of CSE, MITE, Moodabidri Page 41
Computer Network Laboratory 15CSL57

1.<sys/types.h> -prerequisite typedefs.


2. <errno.h> -names for “erno” values (error numbers)
3. <sys/socket.> - struct sock addr ;system prototypes and constants .
4. <netdb.h.h> - network info lookup prototypes and structures.
5. <netinet/in.h> - struct sockaddr_in; byte ordering macros.
6. <arpa/inet.h> - utility function prototypes.
The two key classes from the java.net package used in creation of server and client programs are:
 ServerSocket
 Socket
A server program creates a specific type of socket that is used to listen for client requests (server socket), In
the case of a connection request, the program creates a new socket through which it will exchange data with
the client using input and output streams. The socket abstraction is very similar to the file concept:
developers have to open a socket, perform I/O, and close it.

The steps for creating a simple server program are:


1. Open the Server Socket: ServerSocket server = new ServerSocket( PORT );
2. Wait for the Client Request: Socket client = server.accept();
3. Create I/O streams for communicating to the client
DataInputStream is = new DataInputStream(client.getInputStream());
DataOutputStream os = new DataOutputStream(client.getOutputStream());
4. Perform communication with client Receive from client:
String line = is.readLine();
Send to client: os.writeBytes(“Hello\n”);
5. Close socket: client.close();

The steps for creating a simple client program are:


1. Create a Socket Object: Socket client = new Socket(server, port_id);
2. Create I/O streams for communicating with the server.
is=newDataInputStream(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”);
Dept of CSE, MITE, Moodabidri Page 42
Computer Network Laboratory 15CSL57

4. Close the socket when done: client.close();

INPUT
a) Enter the file name

EXPECTED OUTPUT
a) Print the file content of the request file
b) Print the error condition{requested file does not exit}

PROGRAM: CLIENT SIDE

package contentclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;

public class ContentClient {

public static void main(String[] args) throws IOException{ // TODO code application logic here
Socket sock = new Socket("127.0.0.1", 4000);
System.out.println("Enter the filename ");
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
String fname = reader.readLine();

OutputStream ostream = sock.getOutputStream();


PrintWriter pwriter = new PrintWriter(ostream,true);
pwriter.println(fname);

InputStream istream = sock.getInputStream();


BufferedReader toread = new BufferedReader(new InputStreamReader(istream));
String str ;
while((str=toread.readLine())!=null){
System.out.println(str);
}
pwriter.close();sock.close();toread.close();

PROGRAM: SERVER SIDE

package server;

Dept of CSE, MITE, Moodabidri Page 43


Computer Network Laboratory 15CSL57

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {

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


// TODO code application logic here
ServerSocket serverSocket = new ServerSocket(4000);
System.out.println("Server ready for the connection");
Socket sock = serverSocket.accept();
System.out.println("Connection was successful ");

//to Read the file name from the client


InputStream istream = sock.getInputStream() ;
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(istream));
String fname = bufferedReader.readLine();

//Reading the contents


BufferedReader contentReader = new BufferedReader(new FileReader(fname));
//keeping output stream ready for sending the content
OutputStream ostream = sock.getOutputStream();
PrintWriter pwrite = new PrintWriter(ostream,true);
String str ;
while((str = contentReader.readLine())!=null){
pwrite.println(str);
}
sock.close();serverSocket.close();pwrite.close(); bufferedReader.close();contentReader.close();
}

RESULT:

Dept of CSE, MITE, Moodabidri Page 44


Computer Network Laboratory 15CSL57

Dept of CSE, MITE, Moodabidri Page 45


Computer Network Laboratory 15CSL57

PROGRAM-4
TITLE
Write a program on datagram socket for client/server to display the messages on client side, typed at the
server side.

AIM
To demonstrate the client server {Request and Reply} concept by using UDP Datagram.

DESCRIPTION
A datagram socket is the sending or receiving point for a packet delivery service. Each packet sent or received on a
datagram socket is individually addressed and routed. Multiple packets sent from one machine to another may be
routed differently, and may arrive in any order. One of the examples where UDP is preferred over TCP is the live
coverage of TV channels. In this aspect, we want to transmit as many frames to live audience as possible not worrying
about the loss of one or two frames. TCP being a reliable protocol add its own overhead while transmission.
Datagram packets are used to implement a connectionless packet delivery service supported by the UDP protocol.
Each message is transferred from source machine to destination based on information contained within that packet.
That means, each packet needs to have destination address and each packet might be routed differently, and might
arrive in any order. Packet delivery is not guaranteed.
The format of datagram packet is:
Message length Host Server Port

Java supports datagram communication through the following classes:


 DatagramPacket
 DatagramSocket
The class DatagramPacket contains several constructors that can be used for creating packet object. One of them is:
DatagramPacket(byte[] buf, int length, InetAddress address, int port);

This constructor is used for creating a datagram packet for sending packets of length length to the specifi ed port
number on the specifi ed host. The message to be transmitted is indicated in the fi rst argument.
The key methods of DatagramPacket class are:
 byte[] getData() Returns the data buffer.
 int getLength() Returns the length of the data to be sent or the length of the data received.
 void setData(byte[] buf) Sets the data buffer for this packet.
 void setLength(int length) Sets the length for this packet.
The class DatagramSocket supports various methods that can be used for transmitting or receiving data a datagram
over the network.
The two key methods are:

Dept of CSE, MITE, Moodabidri Page 46


Computer Network Laboratory 15CSL57

void send(DatagramPacket p) Sends a datagram packet from this socket.


void receive(DatagramPacket p) Receives a datagram packet from this socket.
A simple UDP server program that waits for client’s requests and then accepts the message (datagram) and sends back
the same message is given below. Of course, an extended server program can manipulate client’s messages/request and
send a new message as a response.
INPUT
a) Enter the file name

EXPECTED OUTPUT
a) Print the file content of the request file
b) Print the error condition {requested file does not exist}

PROGRAM: CLIENTSIDE

package udpclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;
public class UDPClient {
public static void main(String[] args) throws SocketException, UnknownHostException, IOException {
byte[] sendData = new byte[1024];
byte[] receiveData = new byte[1024];
DatagramSocket mySocket = new DatagramSocket();
System.out.println("Enter the data");
BufferedReader infromUser = new BufferedReader(new InputStreamReader(System.in));
InetAddress myIp = InetAddress.getByName("localhost");

String data = infromUser.readLine();


sendData = data.getBytes();
DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,myIp,9000);
mySocket.send(sendPacket);

DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);


mySocket.receive(receivePacket);

String datatoDisplay = new String(receivePacket.getData());


System.out.println("From server"+datatoDisplay);
mySocket.close();

Dept of CSE, MITE, Moodabidri Page 47


Computer Network Laboratory 15CSL57

PROGRAM: SERVER SIDE

package udpserver;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;
/**
*
* @author prashanth
*/
public class UDPServer {
public static void main(String[] args) throws SocketException, IOException {
DatagramSocket datagramSocket = new DatagramSocket(9000);
byte[] receivedata = new byte[1024];
byte[] senddata = new byte[1024];

while(true){
DatagramPacket recievePacket = new DatagramPacket(receivedata,receivedata.length);
datagramSocket.receive(recievePacket);

String data = new String(recievePacket.getData());


System.out.println("Client Data :"+data);

InetAddress clientIPAddress = recievePacket.getAddress();


int port = recievePacket.getPort();

System.out.println("Enter the data to send to client ");


Scanner scan = new Scanner(System.in);
String datatosend = scan.next();
senddata = datatosend.getBytes();
DatagramPackettoSendtoClient=new DatagramPacket(senddata,senddata.length,clientIPAddress,port);
datagramSocket.send(toSendtoClient);
}

Dept of CSE, MITE, Moodabidri Page 48


Computer Network Laboratory 15CSL57

RESULT

Dept of CSE, MITE, Moodabidri Page 49


Computer Network Laboratory 15CSL57

PROGRAM-5
TITLE

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

AIM
To demonstrate message encryption and Decryption

DESCRIPTION

The RSA Public key algorithm was invented in 1977 by Ron Rivest, Adi Shamir and Leonard Adleman
(RSA). The algorithm Supports Encryption and Digital Signatures. It is the most widely used public key
algorithm. RSA gets its security from the integer factorization problem. The algorithm is relatively easy to
understand and implement. It has been patent free since 2000. RSA is used in security protocols such as
IPSEC/IKE -IP data security, TLS/SSL -transport data security (web), PGP -email security, SSH -terminal
connection security, SILC -conferencing service security.

RSA gets its security from the factorization problem. The difficulty of factoring large numbers is the basis
of security of RSA.The Integer factorization problem (finding a number's prime factors): For a positive
integer n, find its prime factors: n = p1 p2 ... pi where pi is positive distinct prime number Example: 257603
= 41 * 61 * 103 Factorization algorithms can be used to factor faster than brute forcing. Some of them are
Trial division, Pollard's rho, Pollard's p-1, Quadratic sieve, elliptic curve factorization, Random square
factoring, Number field sieve, etc.

A Prime number is a positive integer and is divisible only by itself and 1. Prime numbers are found with
primality testing; an algorithm which tests a probable prime for primality. If primality testing returns false
prime numbers the cryptographic algorithm may be insecure (or will not function correctly).

Key generation:

1)Select random prime numbers p and q, and check that p != q

2)Compute modulus n = pq

3)Compute phi = (p - 1)(q - 1)

4)Select public exponent e, 1 < e < phi such that gcd(e,phi) = 1

5)Compute private exponent d = e^-1 mod phi

Dept of CSE, MITE, Moodabidri Page 50


Computer Network Laboratory 15CSL57

6)Public key is {n, e}, private key is d

Encryption: c = me mod n, decryption: m = cd mod

The selected public exponent e, which is used as public key with n. It is used to encrypt messages and to
verify digital signatures. The e is stored for later with n. The e is usually small number but it can be 1 < e <
phi . The e must be relatively prime to phi , hence gcd(e, phi ) = 1.

(gcd = greatest common divisor, using the Euclidean algorithm)

The private exponent d, is the actual RSA private key. The d must not be disclosed at any time or the
security of the RSA is compromised. The d is found by computing the multiplicative inverse d = e^-1 mod
phi . The extended Euclidean algorithm is commonly used to compute inverses. The d exponent is used to
decrypt messages and to compute digital signatures. Implementations try to find as small d as possible to
make decryption faster. This is fine as long as it is assured that d is about the same size as n. If it is only one
quarter of size it is not considered safe to be used. It is possible to find a smaller d by using lcm(p-1,q-1)
instead of phi (lcm = least common multiple, lcm(p-1,q-1) = phi /gcd(p-1,q-1) ).

Example of RSA with small numbers:

p = 47, q = 71, compute n = pq = 3337

Compute phi = 46 * 70 = 3220

Let e be 79, compute d = 79-1 mod 3220 = 1019

Public key is n and e, private key d, discard p and q.

Encrypt message m = 688, 68879 mod 3337 = 1570 = c.

Decrypt message c = 1570, 15701019 mod 3337 = 688 = m.

INPUT
a) Enter the two large prime number
b) Enter the Value of e
c) Enter the Message

EXPECTED OUTPUT
a) Print the cipher Text
b) Print the plain Text

Dept of CSE, MITE, Moodabidri Page 51


Computer Network Laboratory 15CSL57

PROGRAM: RSA

package rsa;
import java.io.DataInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.util.Random;
/**
*
* @author prashanth
*/
public class RSA {
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 RSA()
{
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 RSA(BigInteger e, BigInteger d, BigInteger N)
{
this.e = e;
this.d = d;
this.N = N;
}
@SuppressWarnings("deprecation")
public static void main(String[] args) throws IOException {
// TODO code application logic here
RSA rsa = new RSA();
DataInputStream in = new DataInputStream(System.in);

String teststring;
System.out.println("Enter the plain text:");
teststring = in.readLine();
System.out.println("Encrypting String: " + teststring);

Dept of CSE, MITE, Moodabidri Page 52


Computer Network Laboratory 15CSL57

System.out.println("String in Bytes: "+ bytesToString(teststring.getBytes()));


// encrypt
byte[] encrypted = rsa.encrypt(teststring.getBytes());
// decrypt
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;
}
// Encrypt message
public byte[] encrypt(byte[] message)
{
return (new BigInteger(message)).modPow(e, N).toByteArray();
}
// Decrypt message
public byte[] decrypt(byte[] message)
{
return (new BigInteger(message)).modPow(d, N).toByteArray();
}
}

RESULT

Dept of CSE, MITE, Moodabidri Page 53


Computer Network Laboratory 15CSL57

PROGRAM-6
TITLE
Write a program for congestion control using Leaky bucket algorithm .
AIM
To control congestion in computer network

DESCRIPTION

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

Dept of CSE, MITE, Moodabidri Page 54


Computer Network Laboratory 15CSL57

INPUT
a) Enter the Bucket Size
b) Enter the flow rate
c) Enter the no of packets and size

EXPECTED OUTPUT
a) Print the Bucket Size
b) Print the flow rate
c) Print the no of packet and size

PROGRAM: LEAKY BUCKET


/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package leakybucket;
import java.util.Scanner;

/**
*
* @author Kokila
*/
public class Leakybucket {

/**
* @param args the command line arguments
*/
public static void main(String[] args) {
Scanner sc= new Scanner(System.in);
System.out.println("Enter the bucket size=");
int n=sc.nextInt();
int a[]=new int[n];
System.out.println("Enter the number of packets=");
int num=sc.nextInt();
System.out.println("Enter the Data rate=");
for(int i=0;i<num;i++)
{
a[i]=sc.nextInt();
}
System.out.println("Enter output rate=");
int out=sc.nextInt();
for(int i=0;i<num;i++)
if(a[i]>n)
{
System.out.println("Bucket overflow\n"+a[i]);
}
else
{
Dept of CSE, MITE, Moodabidri Page 55
Computer Network Laboratory 15CSL57

if (a[i]==out)
System.out.println("Packet transmited"+a[i]);
else if(a[i]>out)
{
while(a[i]!=0 && a[i]>out)
{
System.out.println("Packet transmitted "+out);
a[i]=a[i]-out;
}
System.out.println("Packet transmitted "+a[i]);
}
}
}

RESULT

Dept of CSE, MITE, Moodabidri Page 56

You might also like