Computer Network Laboratorynew
Computer Network Laboratorynew
Computer Network Laboratorynew
LAB MANUAL
For
V SEMESTER B.E (CSE/ISE)
SEMESTER – V
Lab Experiments:
PART A
1. Implement three nodes point – to – point network with duplex links between them. Set the
queue size, vary the bandwidth and find the number of packets dropped.
2. Implement transmission of ping messages/trace route over a network topology consisting
of 6 nodes and find the number of packets dropped due to congestion.
3. Implement an Ethernet LAN using n nodes and set multiple traffic nodes and plot
congestion window for different source / destination.
4. 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.
Features of NS2
NS2 can be employed in most unix systems and windows. Most of the NS2 code is in C++. It
uses TCL as its scripting language, Otcl adds object orientation to TCL.NS(version 2) is an
object oriented, discrete event driven network simulator that is freely distributed and open
source.
• Traffic Models: CBR, VBR, Web etc
• Protocols: TCP, UDP, HTTP, Routing algorithms, MAC etc
• Error Models: Uniform, bursty etc
• Misc: Radio propagation, Mobility models , Energy Models
• Topology Generation tools
• Visualization tools (NAM), Tracing
Structure of NS
NS is an object oriented discrete event simulator
– Simulator maintains list of events and executes one event after another
Dept. of CSE, CEC 2019-20 Page 3
Computer network laboratory 17CSL57
Source code
Most of NS2 code is in C++
Scripting language
It uses TCL as its scripting language OTcl adds object orientation to TCL.
Basics of TCL
Syntax: command arg1 arg2 arg3
Hello World!
puts stdout{Hello, World!}
Hello, World!
Simple Arithmetic
expr 7.2 / 4
Procedures
proc Diag {a b} {
set c [expr sqrt($a * $a + $b * $b)]
return $c }
puts "Diagonal of a 3, 4 right triangle is [Diag 3 4]"
Output: Diagonal of a 3, 4 right triangle is 5.0
Loops
while{$i < $n} { for {set i 0} {$i < $n} {incr i} {
... ...
} }
NS Simulator Procedure:
STEP 1: Start
STEP 2: Create the simulator object ns for designing the given simulation
STEP 3: Open the trace file and nam file in the write mode
STEP 4: Create the nodes of the simulation using the ‘set’ command
STEP 5: Create links to the appropriate nodes using $ns duplex-link command
STEP 6: Set the orientation for the nodes in the simulation using ‘orient’ command
STEP 7: Create TCP agent for the nodes and attach these agents to the nodes
STEP 8: The traffic generator used is FTP for both node0 and node1
STEP 9: Configure node1 as the sink and attach it
STEP10: Connect node0 and node1 using ‘connect’ command
STEP 11: Setting color for the nodes
STEP 12: Schedule the events for FTP agent 10 sec
STEP 13: Schedule the simulation for 5 minutes
This line declares a new variable as using the set command, you can call this variable as you
wish, In general people declares it as ns because it is an instance of the Simulator class, so an
object the code[new Simulator] is indeed the installation of the class Simulator using the
reserved word new. In order to have output files with data on the simulation (trace files) or files
used for visualization (nam files), we need to create the files using "open "command:
The above creates a dta trace file called "out.tr" and a nam visualization trace file called
"out.nam". Within the tcl script, these files are not called explicitly by their names, but
instead by pointers that are declared above and called "tracefile1" and "namfile" respectively.
Remark that they begins with a # symbol. The second line open the file "out.tr" to be used for
writing, declared with the letter "w". The third line uses a simulator method called trace-all
that have as parameter the name of the file where the traces will go. The last line tells the
simulator to record all simulation traces in NAM input format. It also gives the file name that
the trace will be written to later by the command $ns flush-trace. In our case, this will be the
file pointed at by the pointer "$namfile", i.e the file "out.tr". The termination of the program
is done using a "finish" procedure.
The word proc declares a procedure in this case called finish and without arguments. The
word global is used to tell that we are using variables declared outside the procedure. The
simulator method "flush-trace” will dump the traces on the respective files. The tcl command
"close” closes the trace files defined before and exec executes the nam program for
visualization. The command exit will ends the application and return the number 0 as status
to the system. Zero is the default for a clean exit. Other values can be used to say that is a exit
because something fails. At the end of ns program we should call the procedure "finish" and
specify at what time the termination should occur. For example,
will be used to call "finish" at time 125sec. Indeed, the at method of the simulator allows us
to schedule events explicitly.
The simulation can then begin using the command
The node is created which is printed by the variable n0. When we shall refer to that node in
the script we shall thus write $n0. Once we define several nodes, we can define the links that
connect them.
Creating link between nodes:
$ns <link_type> $n0 $n1 <bandwidth> <delay><queue-type>
An example of a definition of a link is:
Which means that $n0 and $n2 are connected using a bi-directional link that has 10ms of
propagation delay and a capacity of 10Mb per sec for each direction. To define a directional
link instead of a bi-directional one, we should replace "duplex-link" by "simplexlink".
In NS, an output queue of a node is implemented as a part of each link whose input is that
node. The definition of the link then includes the way to handle overflow at that queue. In our
case, if the buffer capacity of the output queue is exceeded then the last packet to arrive is
dropped. Many alternative options exist, such as the RED (Random Early Discard)
mechanism, the FQ (Fair Queuing), the DRR (Deficit Round Robin), the stochastic Fair
Queuing (SFQ) and the CBQ (which including a priority and a round-robin scheduler).
In ns, an output queue of a node is implemented as a part of each link whose input is that
node. We should also define the buffer capacity of the queue related to each link. An example
would be:
The command $ns attach-agent $n0 $tcp defines the source node of the tcp connection.
The command
Defines the behavior of the destination node of TCP and assigns to it a pointer called sink.
#Setup a UDP connection
TCP has many parameters with initial fixed defaults values that can be changed if mentioned
explicitly. For example, the default TCP packet size has a size of 1000bytes. This can be
changed to another value, say 552bytes, using the command $tcp set packetSize_ 552.
CBR over UDP
A UDP source and destination is defined in a similar way as in the case of TCP. Instead of
defining the rate in the command $cbr set rate_ 0.01Mb, one can define the time interval
between transmission of packets using the command.
Scheduling Events
NS is a discrete event based simulation. The tcp script defines when event should occur. The
initializing command set ns [new Simulator] creates an event scheduler, and events are then
scheduled using the format:
The scheduler is started when running ns that is through the command $ns run. The beginning
and end of the FTP and CBR application can be done through the following command
1. The first field is the event type. It is given by one of four possible symbols r, +, -, d which
correspond respectively to receive (at the output of the link), enqueued, dequeued and
dropped.
2. The second field gives the time at which the event occurs.
3. Gives the input node of the link at which the event occurs.
4. Gives the output node of the link at which the event occurs.
5. Gives the packet type (eg CBR or TCP)
6. Gives the packet size
7. Some flags
8. This is the flow id (fid) of IPv6 that a user can set for each flow at the input OTcl script
one can further use this field for analysis purposes; it is also used when specifying stream
color for the NAM display.
9. This is the source address given in the form of "node.port".
10. This is the destination address, given in the same form.
11. This is the network layer protocol’s packet sequence number. Even though UDP
implementations in a real network do not use sequence number, ns keeps track of UDP packet
sequence number for analysis purposes
12. The last field shows the Unique id of the packet.
XGRAPH
The xgraph program draws a graph on an x-display given data read from either data file or
from standard input if no files are specified. It can display upto 64 independent data sets
using different colors and line styles for each set. It annotates the graph with a title, axis
labels, grid lines or tick marks, grid labels and a legend.
Syntax:
Awk- An Advanced
awk is a programmable, pattern-matching, and processing tool available in UNIX. It works
equally well with text and numbers. awk is not just a command, but a programming language
too. In other words, awk utility is a pattern scanning and processing language. It searches one
or more files to see if they contain lines that match specified patterns and then perform
associated actions, such as writing the line to the standard output or incrementing a counter
each time it finds a match.
Syntax:
before processing the first line, for example, a heading, then the BEGIN section can be used
gainfully. Similarly, the end section useful in printing some totals after processing is over.
The BEGIN and END sections are optional and take the form
BEGIN {action}
END {action}
These two sections, when present, are delimited by the body of the awk program. You can
use them to print a suitable heading at the beginning and the average salary at the end.
Aim: Simulate a three node point to point network with duplex links between them. Set queue size
and vary the bandwidth and find number of packets dropped.
Program: prog1.tcl
set ns [new Simulator] # Letter S is capital
proc finish { } {
global ns nf nd
$ns flush-trace # clears trace file contents
close $nf
close $nd
exec nam prog1.nam &
exit 0
}
AWK file: (Open a new editor using “gedit command” and write awk file and save with
“.awk” extension) #immediately after BEGIN should open braces „{„
BEGIN {
dcount = 0;
rcount = 0;
}
{
event = $1;
if(event == "d")
{
dcount++;
}
if(event == "r")
{
rcount++;
}}
END { printf("no of pckts dropped=%d\n",dcount);
printf("no of pckts recieved=%d\n",rcount);
}
Topology
Contents of Trace
File
Output
Experiment No: 2 Transmission of Ping Messages over a Six Nodes Network Topology
Aim: Simulate transmission of ping messages/trace route over a network topology consisting of 6
nodes and find the number of packets dropped due to congestion.
Program:Prog2.tcl
AWK file:
BEGIN{
pingDrop=0;
}
{
if($1= ="d" )
{
pingDrop++;
}
}
END{ printf("Total number of ping packets dropped due to congestion is
=%d\n",pingDrop);
}
Topology
Output
Note: Vary the bandwidth and queue size between the nodes n0-n2 , n2-n4. n6-n2 and n2- n5
and see the number of packets dropped at the nodes.
Program:prog3.tcl
$ns make-lan "$n0 $n1 $n2 $n3 $n4" 100Mb 100ms LL Queue/DropTail Mac/802_3
$ns duplex-link $n4 $n5 1Mb 1ms DropTail
proc finish { } {
global ns nf tf
$ns flush-trace
close $tf
close $nf
exec nam prog3.nam &
exit 0
}
AWK file :
cwnd:- means congestion window
BEGIN { } {
if($6= ="cwnd_") / * don’t leave space after writing cwnd_ */
printf("%f\t%f\t\n",$1,$7); /* put \n in printf */
} END { }
Topology Graph
create-god 3
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
$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
AWK file:
BEGIN{
count1=0
count2=0
pack1=0
pack2=0
time1=0
time2=0
}
{ if($1= ="r"&& $3= ="_1_" && $4= ="AGT")
{ count1++
pack1=pack1+$8
time1=$2 }
if($1= ="r" && $3= ="_2_" && $4= ="AGT")
{ count2++
pack2=pack2+$8
time2=$2 }
}
END{
printf("The Throughput from n0 to n1: %f Mbps \n”,
((count1*pack1*8)/(time1*1000000)));
printf("The Throughput from n1 to n2: %f Mbps",
((count2*pack2*8)/(time2*1000000)));
}
Second Generation (2G) technology is based on the technology known as global system for
mobile communication (GSM). This technology enabled various networks to provide services
like text messages, picture messages and MMS.
The technologies used in 2G are either TDMA (Time Division Multiple Access) which
divides signal into different time slots or CDMA (Code Division Multiple Access) which
allocates a special code to each user so as to communicate over a multiplex physical channel.
GSM uses a variation of time division multiple access (TDMA). 2G networks developed as a
replacement for first generation (1G) analog cellular networks, and the GSM standard
originally described as a digital, circuit-switched network optimized for full duplex voice
telephony. This expanded over time to include data communications, first by circuit-switched
transport, then by packet data transport via GPRS (General Packet Radio Services).
GSM can be implemented on all the versions of NS2 (Since year 2004: ns-2.27, and later
versions of NS2)
# General Parameters
set opt(title) zero ;
set opt(stop) 100 ;# Stop time.
set opt(ecn) 0 ;
# Topology
set opt(type) gsm ;#type of link:
set opt(secondDelay) 55 ;# average delay of access links in ms
# AQM parameters
set opt(minth) 30 ;
set opt(maxth) 0 ;
set opt(adaptive) 1 ;# 1 for Adaptive RED, 0 for plain RED
# Traffic generation.
set opt(flows) 0 ;# number of long-lived TCP flows
set opt(window) 30 ;# window for long-lived traffic
set opt(web) 2 ;# number of web sessions
# Plotting statistics.
set opt(quiet) 0 ;# popup anything?
set opt(wrap) 100 ;# wrap plots?
set opt(srcTrace) is ;# where to plot traffic
set opt(dstTrace) bs2 ;# where to plot traffic
set opt(gsmbuf) 10 ; # buffer size for gsm
proc cell_topo {} {
global ns nodes
$ns duplex-link $nodes(lp) $nodes(bs1) 3Mbps 10ms 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 50ms DropTail
puts "Cell Topology"
}
proc set_link_params {t} {
global ns nodes bwUL bwDL propUL propDL buf
$ns bandwidth $nodes(bs1) $nodes(ms) $bwDL($t) simplex
$ns bandwidth $nodes(ms) $nodes(bs1) $bwUL($t) simplex
$ns bandwidth $nodes(bs2) $nodes(ms) $bwDL($t) simplex
$ns bandwidth $nodes(ms) $nodes(bs2) $bwUL($t) simplex
$ns delay $nodes(bs1) $nodes(ms) $propDL($t) simplex
$ns delay $nodes(ms) $nodes(bs1) $propDL($t) simplex
$ns delay $nodes(bs2) $nodes(ms) $propDL($t) simplex
$ns delay $nodes(ms) $nodes(bs2) $propDL($t) simplex
$ns queue-limit $nodes(bs1) $nodes(ms) $buf($t)
$ns queue-limit $nodes(ms) $nodes(bs1) $buf($t)
$ns queue-limit $nodes(bs2) $nodes(ms) $buf($t)
$ns queue-limit $nodes(ms) $nodes(bs2) $buf($t)
}
# RED and TCP parameters
Queue/RED set summarystats_ true
Queue/DropTail set summarystats_ true
Queue/RED set adaptive_ $opt(adaptive)
Queue/RED set q_weight_ 0.0
Queue/RED set thresh_ $opt(minth)
Queue/RED set maxthresh_ $opt(maxth)
Queue/DropTail set shrink_drops_ true
Agent/TCP set ecn_ $opt(ecn)
Agent/TCP set window_ $opt(window)
DelayLink set avoidReordering_ true
source web.tcl
#Create topology
switch $opt(type) {
gsm -
gprs -
umts {cell_topo}
}
set_link_params $opt(type)
$ns insert-delayer $nodes(ms) $nodes(bs1) [new Delayer]
$ns insert-delayer $nodes(bs1) $nodes(ms) [new Delayer]
$ns insert-delayer $nodes(ms) $nodes(bs2) [new Delayer]
$ns insert-delayer $nodes(bs2) $nodes(ms) [new Delayer]
proc stop {} {
global nodes opt nf
set wrap $opt(wrap)
set sid [$nodes($opt(srcTrace)) id]
set did [$nodes($opt(dstTrace)) id]
if {$opt(srcTrace) == "is"} {
set a "-a out.tr"
} else {
set a "out.tr"
}
set GETRC "../../../bin/getrc"
set RAW2XG "../../../bin/raw2xg"
Aim: Simulate and study the performance of CDMA on NS2/NS3 (Using stack called Call net) or equivalent
environment.
3G networks developed as a replacement for second generation (2G) GSM standard network
with full duplex voice telephony.
CDMA is used as the access method in many mobile phone standards. IS-95, also called
cdmaOne, and its 3G evolution CDMA2000, are often simply referred to as CDMA, but
UMTS(The Universal Mobile Telecommunications System is a third generation mobile
cellular system for networks based on the GSM standard.), the 3G standard used by GSM
carriers, also uses wideband CDMA.
Long-Term Evolution (LTE) is a standard for high-speed wireless communication which
uses CDMA network technology. 3G technology generally refers to the standard of
accessibility and speed of mobile devices.
The standards of the technology were set by the International Telecommunication Union
(ITU). This technology enables use of various services like GPS (Global Positioning System),
mobile television and video conferencing. It not only enables them to be used worldwide, but
also provides with better bandwidth and increased speed. The main aim of this technology is
to allow much better coverage and growth with minimum investment.
CDMA can be implemented on all the versions of NS2 (Since year 2004: ns-2.27, and later
versions of NS2)
# General Parameters
set opt(title) zero ;
set opt(stop) 100 ;# Stop time.
set opt(ecn) 0 ;
# Topology
set opt(type) umts ;#type of link:
set opt(secondDelay) 55 ;# average delay of access links in ms
# AQM parameters
set opt(minth) 30 ;
set opt(maxth) 0 ;
set opt(adaptive) 1 ;# 1 for Adaptive RED, 0 for plain RED
# Traffic generation.
set opt(flows) 0 ;# number of long-lived TCP flows
set opt(window) 30 ;# window for long-lived traffic
set opt(web) 2 ;# number of web sessions
# Plotting statistics.
set opt(quiet) 0 ;# popup anything?
set opt(wrap) 100 ;# wrap plots?
set opt(srcTrace) is ;# where to plot traffic
set opt(dstTrace) bs2 ;# where to plot traffic
set opt(umtsbuf) 10 ; # buffer size for umts
proc cell_topo {} {
global ns nodes
$ns duplex-link $nodes(lp) $nodes(bs1) 3Mbps 10ms 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 50ms DropTail
puts "Cell Topology"
}
proc set_link_params {t} {
global ns nodes bwUL bwDL propUL propDL buf
$ns bandwidth $nodes(bs1) $nodes(ms) $bwDL($t) simplex
$ns bandwidth $nodes(ms) $nodes(bs1) $bwUL($t) simplex
$ns delay $nodes(bs1) $nodes(ms) $propDL($t) simplex
$ns delay $nodes(ms) $nodes(bs1) $propDL($t) simplex
$ns queue-limit $nodes(bs1) $nodes(ms) $buf($t)
$ns queue-limit $nodes(ms) $nodes(bs1) $buf($t)
$ns bandwidth $nodes(bs2) $nodes(ms) $bwDL($t) simplex
$ns bandwidth $nodes(ms) $nodes(bs2) $bwUL($t) simplex
$ns delay $nodes(bs2) $nodes(ms) $propDL($t) simplex
$ns delay $nodes(ms) $nodes(bs2) $propDL($t) simplex
$ns queue-limit $nodes(bs2) $nodes(ms) $buf($t)
$ns queue-limit $nodes(ms) $nodes(bs2) $buf($t)
}
source web.tcl
#Create topology
switch $opt(type) {
umts {cell_topo}
}
set_link_params $opt(type)
$ns insert-delayer $nodes(ms) $nodes(bs1) [new Delayer]
$ns insert-delayer $nodes(bs1) $nodes(ms) [new Delayer]
$ns insert-delayer $nodes(ms) $nodes(bs2) [new Delayer]
$ns insert-delayer $nodes(bs2) $nodes(ms) [new Delayer]
proc stop {} {
global nodes opt nf
set wrap $opt(wrap)
set sid [$nodes($opt(srcTrace)) id]
set did [$nodes($opt(dstTrace)) id]
if {$opt(srcTrace) == "is"} {
set a "-a out.tr"
} else {
set a "out.tr"
}
set GETRC "../../../bin/getrc"
set RAW2XG "../../../bin/raw2xg"
PART B
Aim: A program for error detecting code using CRC-CCITT (16- bits).
Theory
The cyclic redundancy check, or CRC, is a technique for detecting errors in digital data, but
not for making corrections when errors are detected. It is used primarily in data transmission.
In the CRC method, a certain number of check bits, often called a checksum, are appended to
the message being transmitted. The receiver can determine whether or not the check bits
agree with the data, to ascertain with a certain degree of probability whether or not an error
occurred in transmission.
Source Code:
import java.io.*;
class crc_gen
{
public static void main(String args[]) throws IOException
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
int[] data;
int[] div;
int[] divisor;
int[] rem;
int[] crc;
int data_bits, divisor_bits, tot_length;
tot_length=data_bits+divisor_bits-1;
div=new int[tot_length];
rem=new int[tot_length];
crc=new int[tot_length];
/*------------------ CRC GENERATION-----------------------*/
for(int i=0;i<data.length;i++)
div[i]=data[i];
System.out.println();
System.out.println("CRC code : ");
for(int i=0;i<crc.length;i++)
System.out.print(crc[i]);
/*-------------------ERROR DETECTION---------------------*/
System.out.println();
System.out.println("Enter CRC code of "+tot_length+" bits : ");
for(int i=0; i<crc.length; i++)
crc[i]=Integer.parseInt(br.readLine());
cur++;
if((rem.length-cur)<divisor.length)
break;
}
return rem;
}
}
OUTPUT :
Enternumber of data bits :
7
Enter data bits :
1
0
1
1
0
0
1
Enter number of bits in divisor :
3
Enter Divisor bits :
1
0
1
Data bits are : 1011001
divisor bits are : 101
Dividend (after appending 0's) are : 101100100
CRC code :
101100111
Enter CRC code of 9 bits :
1
0
1
1
0
0
1
0
1
crc bits are : 101100101
Error
Aim: Implement a program to find the shortest path between vertices using bellman-ford
algorithm
Distance Vector Algorithm is a decentralized routing algorithm that requires that each router
simply inform its neighbors of its routing table. For each network path, the receiving routers
pick the neighbor advertising the lowest cost, then add this entry into its routing table for re-
advertisement.
To find the shortest path, Distance Vector Algorithm is based on one of two basic
algorithms: the Bellman-Ford and the Dijkstra algorithms. Routers that use this algorithm
have to maintain the distance tables (which is a one- dimension array -- "a vector"), which
tell the distances and shortest path to sending packets to each node in the network. The
information in the distance table is always up date by exchanging information with the
neighboring nodes. The number of data in the table equals to that of all nodes in networks
(excluded itself). The columns of table represent the directly attached neighbors whereas the
rows represent all destinations in the network. Each data contains the path for sending
packets to each destination in the network and distance/or time to transmit on that path (we
call this as "cost"). The measurements in this algorithm are the number of hops, latency, the
number of outgoing packets, etc.
Program:
import java.util.Scanner;
public class BellmanFord
{
private int D[]; private int num_ver;
public static final int MAX_VALUE = 999;
public BellmanFord(int num_ver)
{
this.num_ver = num_ver; D = new int[num_ver + 1];
}
{
D[node] = MAX_VALUE;
}
D[source] = 0;
for (int node = 1; node <= num_ver - 1; node++)
{
for (int sn = 1; sn <= num_ver; sn++)
{
for (int dn = 1; dn <= num_ver; dn++)
{
if (A[sn][dn] != MAX_VALUE)
{
if (D[dn] > D[sn]+ A[sn][dn])
D[dn] = D[sn] + A[sn][dn];
}
}
}
}
for (int sn = 1; sn <= num_ver; sn++)
{
for (int dn = 1; dn <= num_ver; dn++)
{
if (A[sn][dn] != MAX_VALUE)
{
if (D[dn] > D[sn]+ A[sn][dn])
System.out.println("The Graph contains
negative egde cycle");
}
}
}
for (int vertex = 1; vertex <= num_ver; vertex++)
{
System.out.println("distance of source " + source + " to "+ vertex +
" is " + D[vertex]);
}
}
public static void main(String[ ] args)
{
int num_ver = 0; int source;
Scanner scanner = new Scanner(System.in); System.out.println("Enter the
number of vertices");
num_ver = scanner.nextInt();
int A[][] = new int[num_ver + 1][num_ver + 1]; System.out.println("Enter
the adjacency matrix");
for (int sn = 1; sn <=num_ver; sn++)
{
for (int dn = 1; dn <= num_ver; dn++)
{
A[sn][dn] = scanner.nextInt(); if (sn == dn)
{
A[sn][dn] = 0; continue;
}
if (A[sn][dn] == 0)
{
A[sn][dn] = MAX_VALUE;
}
}
}
System.out.println("Enter the source vertex"); source = scanner.nextInt();
BellmanFord b = new BellmanFord (num_ver);
b.BellmanFordEvaluation(source, A); scanner.close();
}
}
Output:
Aim: Using TCP/IP sockets, write a client – server program to make the client send the file name
and to make the server send back the contents of the requested file if present. Implement the
above program using as message queues or FIFOs as IPC channels.
Client Program:
import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.Scanner;
class Client
{
public static void main(String args[])throws Exception
{
String address = "";
Scanner sc=new Scanner(System.in);
System.out.println("Enter Server Address: ");
address=sc.nextLine();
//create the socket on port 5000
Socket s=new Socket(address,5000);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Send Get to start...");
String str="",filename="";
try
{
while(!str.equals("start"))
str=br.readLine();
dout.writeUTF(str);
dout.flush();
filename=din.readUTF();
System.out.println("Receving file: "+filename);
filename="client"+filename;
System.out.println("Saving as file: "+filename);
long sz=Long.parseLong(din.readUTF());
System.out.println ("File Size: "+(sz/(1024*1024))+" MB");
byte b[]=new byte [1024];
System.out.println("Receving file..");
FileOutputStream fos=new FileOutputStream(new
File(filename),true);
long bytesRead;
do
{
bytesRead = din.read(b, 0, b.length);
fos.write(b,0,b.length);
}while(!(bytesRead<1024));
System.out.println("Comleted");
fos.close();
dout.close();
s.close();
}
catch(EOFException e)
{
//do nothing
}
}
}
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
class Server
{
public static void main(String args[])throws Exception
{
String filename;
System.out.println("Enter File Name: ");
Scanner sc=new Scanner(System.in);
filename=sc.nextLine();
sc.close();
while(true)
{
//create server socket on port 5000
ServerSocket ss=new ServerSocket(5000);
System.out.println ("Waiting for request");
Socket s=ss.accept();
System.out.println ("Connected With "+s.getInetAddress().toString());
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
try
{
String str="";
str=din.readUTF();
System.out.println("SendGet....Ok");
if(!str.equals("stop"))
{
System.out.println("Sending File: "+filename);
dout.writeUTF(filename);
dout.flush();
File f=new File(filename);
FileInputStream fin=new FileInputStream(f);
long sz=(int) f.length();
byte b[]=new byte [1024];
int read;
dout.writeUTF(Long.toString(sz));
dout.flush();
System.out.println ("Size: "+sz);
System.out.println ("Buf size:
"+ss.getReceiveBufferSize());
while((read = fin.read(b)) != -1)
{
dout.write(b, 0, read);
dout.flush();
}
fin.close();
System.out.println("..ok");
dout.flush();
}
dout.writeUTF("stop");
System.out.println("Send Complete");
dout.flush();
}
catch(Exception e)
{
e.printStackTrace();
System.out.println("An error occured");
}
din.close();
s.close();
ss.close();
}
}
}
Note: Create two different files Client.java and Server.java. Follow the steps given:
1. Open a terminal run the server program and provide the filename to send
2. Open one more terminal run the client program and provide the IP address of the server. We can
give localhost address “127.0.0.1” as it is running on same machine or give the IP address of the
machine.
3. Send any start bit to start sending file.
4. Refer https://www.tutorialspoint.com/java/java_networking.htm for all the
parameters, methods description in socket communication.
Output:
At server Side:
At client side:
Aim: Write a program on datagram socket for client/server to display the messages on client side,
typed at the server side.
A datagram socket is the one for 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.
Source Code:
import java.io.*;
import java.net.*;
public class UDPC
{
public static void main(String[] args)
{
DatagramSocket skt; try
{
skt=new DatagramSocket();
String msg= "text message ";
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)
{
}
}
}
UDP Server
Note: Create two different files UDPC.java and UDPS.java. Follow the following steps:
1. Open a terminal run the server program.
2. Open one more terminal run the client program, the sent message will be received.
Output:
At Server side:
At Client side:
Aim: Implement a program for simple RSA algorithm to encrypt and decrypt the data.
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.
import java.math.BigInteger;
import java.util.*;
class RSAEncDec
{
public static void main(String[] args)
{
BigInteger bigB_pubkey = new BigInteger(args[0]);
BigInteger bigB_prvkey = new BigInteger(args[1]);
BigInteger bigB_n = new BigInteger(args[2]);
int asciiVal=Integer.parseInt(args[3]);
BigInteger bigB_val=new BigInteger(""+asciiVal);
BigInteger bigB_cipherVal=bigB_val.modPow(bigB_pubkey,bigB_n);
System.out.println("Cipher text: " + bigB_cipherVal);
BigInteger bigB_plainVal=bigB_cipherVal.modPow(bigB_prvkey,bigB_n);
int plainVal=bigB_plainVal.intValue();
System.out.println("Plain text:" + plainVal);
}
}
import java.util.*;
import java.math.BigInteger; import java.lang.*;
class RSAkeygen
{
public static void main(String[] args)
{
Random rand1=new Random(System.currentTimeMillis());
Random rand2=new Random(System.currentTimeMillis()*10);
int pubkey=Integer.parseInt(args[0]);
BigInteger bigB_p=BigInteger.probablePrime(32, rand1);
BigInteger bigB_q=BigInteger.probablePrime(32, rand2);
BigInteger bigB_n=bigB_p.multiply(bigB_q);
BigInteger bigB_p_1=bigB_p.subtract(new BigInteger("1"));
BigInteger bigB_q_1=bigB_q.subtract(new BigInteger("1"));
BigInteger bigB_p_1_q_1=bigB_p_1.multiply(bigB_q_1);
while(true)
{
BigInteger BigB_GCD=bigB_p_1_q_1.gcd(new
BigInteger(""+pubkey));
if(BigB_GCD.equals(BigInteger.ONE))
{
break;
}
pubkey++;
}
BigInteger bigB_pubkey=new BigInteger(""+pubkey);
BigInteger bigB_prvkey=bigB_pubkey.modInverse(bigB_p_1_q_1);
System.out.println("public key : "+bigB_pubkey+","+bigB_n);
System.out.println("private key : "+bigB_prvkey+","+bigB_n);
}
}
Aim: Implement a program for congestion control using leaky bucket algorithm.
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)).
While leaky bucket eliminates completely bursty traffic by regulating the incoming
data flow its main drawback is that it drops packets if the bucket is full. Also, it doesn’t take
into account the idle process of the sender which means that if the host doesn’t transmit data
for some time the bucket becomes empty without permitting the transmission of any packet.
Implementation Algorithm:
Steps:
1. Read The Data For Packets
2. Read The Queue Size
3. Divide the Data into Packets
4. Assign the random Propagation delays for each packets to input into the bucket
(input_packet).
5. wlile((Clock++<5*total_packets)and
(out_packets< total_paclets))
a. if (clock == input_packet)
i. insert into Queue
b. if (clock % 5 == 0 )
i. Remove packet from Queue
6. End
Source code:
import java.io.*;
import java.util.*;
class Queue
{
int q[],f=0,r=0,size;
void insert(int n)
{
Scanner in = new Scanner(System.in); q=new int[10];
for(int i=0;i<n;i++)
{
System.out.print("\nEnter " + i + " element: ");
int ele=in.nextInt();
if(r+1>10)
{
System.out.println("\nQueue is full \nLost Packet: "+ele);
break;
}
else
{
r++;
q[i]=ele;
}}}
void delete()
{
Scanner in = new Scanner(System.in); Thread t=new Thread();
if(r==0)
System.out.print("\nQueue empty ");
else
{
for(int i=f;i<r;i++)
{
try
{
t.sleep(1000);
}
catch(Exception e){}
System.out.print("\nLeaked Packet: "+q[i]);
f++;
}
}
System.out.println();
}
}
class Leaky extends Thread
{
public static void main(String ar[]) throws Exception
{
Queue q=new Queue();
Scanner src=new Scanner(System.in);
System.out.println("\nEnter the packets to be sent:");
int size=src.nextInt();
q. insert(size); q.delete();
}
}
Output:
13) How does a network topology affect your decision in setting up a network?
Network topology dictates what media you must use to interconnect devices. It also
serves as basis on what materials, connector and terminations that is applicable for the
setup.
14) What are different ways of securing a computer network?
There are several ways to do this. Install reliable and updated anti-virus program on all
computers. Make sure firewalls are setup and configured properly. User authentication
will also help a lot. All of these combined would make a highly secured network.
15) What is NIC?
NIC is short for Network Interface Card. This is a peripheral card that is attached to a PC
in order to connect to a network. Every NIC has its own MAC address that identifies the
PC on the network.
16) What is WAN?
WAN stands for Wide Area Network. It is an interconnection of computers and devices
that are geographically dispersed. It connects networks that are located in different
regions and countries.
17) What is the importance of the OSI Physical Layer?
The physical layer does the conversion from data bits to electrical signal, and vice versa.
This is where network devices and cable types are considered and setup.
18) How many layers are there under TCP/IP?
There are four layers: the Network Layer, Internet Layer, Transport Layer and
Application Layer.
19) What are proxy servers and how do they protect computer networks?
Proxy servers primarily prevent external users who identifying the IP addresses of an
internal network. Without knowledge of the correct IP address, even the physical
location of the network cannot be identified. Proxy servers can make a network
virtually invisible to external users.
20) What is OSI and what role does it play in computer networks?
OSI (Open Systems Interconnect) serves as a reference model for data communication.
It is made up of 7 layers, with each layer defining a particular aspect on how network
devices connect and communicate with one another. One layer may deal with the
physical media used, while another layer dictates how data is actually transmitted
across the network.
21) What are MAC addresses?
MAC, or Media Access Control, uniquely identifies a device on the network. It is also
known as physical address or Ethernet address. A MAC address is made up of 6-byte
parts.
22) What is the equivalent layer or layers of the TCP/IP Application layer in terms
of OSI reference model?
The TCP/IP Application layer actually has three counterparts on the OSI model: the
Session layer, Presentation Layer and Application Layer.
23) How can you identify the IP class of a given IP address?
By looking at the first octet of any given IP address, you can identify whether it's Class A,
B or C. If the first octet begins with a 0 bit, that address is Class A. If it begins with bits
10 then that address is a Class B address. If it begins with 110, then it's a Class C
network.
24) What are firewalls?
Firewalls serve to protect an internal network from external attacks. These external
threats can be hackers who want to steal data or computer viruses that can wipe out
data in an instant. It also prevents other users from external networks from gaining
access to the private network.
25) Describe at one disadvantage of a peer to peer network.
When you are accessing the resources that are shared by one of the workstations on the
network, that workstation takes a performance hit.
26) What is Hybrid Network?
A hybrid network is a network setup that makes use of both client-server and peer-to-
peer architecture.
27) What is TCP/IP?
TCP/IP is short for Transmission Control Protocol / Internet Protocol. This is a set of
protocol layers that is designed to make data exchange possible on different types of
computer networks, also known as heterogeneous network.
28) How can you manage a network using a router?
Routers have built in console that lets you configure different settings, like security and
data logging. You can assign restrictions to computers, such as what resources it is
allowed access, or what particular time of the day they can browse the internet. You can
even put restrictions on what websites are not viewable across the entire network.
29) What protocol can be applied when you want to transfer files between
different platforms, such between UNIX systems and Windows servers?
Use FTP (File Transfer Protocol) for file transfers between such different servers. This is
possible because FTP is platform independent.
30) What is Ping?
Ping is a utility program that allows you to check connectivity between network devices
on the network. You can ping a device by using its IP address or device name, such as a
computer name.
31) What is peer to peer?
Peer to peer are networks that does not reply on a server. All PCs on this network act as
individual workstations.
32) What is DNS?
DNS is Domain Name System. The main function of this network service is to provide
host names to TCP/IP address resolution.
33) What is the difference between a hub and a switch?
A hub acts as a multiport repeater. However, as more and more devices connect to it, it
would not be able to efficiently manage the volume of traffic that passes through it. A
switch provides a better alternative that can improve the performance especially when
high traffic volume is expected across all ports.
34) What protocols fall under the Application layer of the TCP/IP stack?
The following are the protocols under TCP/IP Application layer: FTP, TFTP, Telnet and
SMTP.
35) You need to connect two computers for file sharing. Is it possible to do this
without using a hub or router?
Yes, you can connect two computers together using only one cable. A crossover type
cable can be use in this scenario. In this setup, the data transmit pin of one cable is
connected to the data receive pin of the other cable, and vice versa.
36) What is ipconfig?
55) What is the difference between a NULL pointer and a void pointer?
A NULL pointer is a pointer of any type whose value is zero. A void pointer is a pointer
to an object of an unknown type, and is guaranteed to have enough bits to hold a pointer
to any object. A void pointer is not guaranteed to have enough bits to point to a function.
61) What type of ICMP packet is send when a ping request is initiated?
ICMP request.
62) If a system is not responding to ping requests, what could be a possible reason
A firewall would be blocking ping requests.
The correction of errors is more difficult than the detection. In error detection, checks
only any error has occurred. In error correction, the exact number of bits that are
corrupted and location in the message are known. The number of the errors and the size
of the message are important factors
Short form of Global System for Mobile Communications, is a wireless network system
A standard for digital cellular mobile communications International roaming
arrangements are enabled among mobile network operators, by providing the
subscribers to use their personal mobile phones anywhere in the world.