LM - CN Lab
LM - CN Lab
LM - CN Lab
LAB MANUAL
PES School
Course objectives:
• Demonstrate operation of network and its management commands
• Simulate and demonstrate the performance of GSM and CDMA
• Implement data link layer and transport layer protocols.
For the experiments below modify the topology and parameters set for the experiment and
take multiple rounds of reading and analyze the results available in log files. Plot necessary
graphs and conclude using any suitable tool.
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
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.24
Part A - SIMULATION USING NS-2
Introduction to NS-2:
NS2 is an open-source simulation tool that runs on Linux. It is a discreet event
simulator targeted at networking research and provides substantial support for simulation of
routing, multicast protocols and IP protocols, such as UDP, TCP, RTP and SRM over
wired and wireless (local and satellite) networks.
Widely known as NS2, is simply an event driven simulation tool.
Useful in studying the dynamic nature of communication networks.
Simulation of wired as well as wireless network functions and protocols (e.g.,
routing algorithms, TCP, UDP) can be done using NS2.
In general, NS2 provides users with a way of specifying such network protocols and
simulating their corresponding behaviors.
Basic syntax
Variables
Tcl allows you to store values in variables and use the values later in commands.
The set command is used to write and read variables. For example, the following command
modifies the variable x to hold the value 32:
set x 32
The command returns the new value of the variable. You can read the value of a
variable by invoking set with only a single argument:
set x
You don't need to declare variables in Tcl: a variable is created automatically the
first time it is set. Tcl variables don't have types: any variable can hold any value.
To use the value of a variable in a command, use variable substitution as in the
following example:
expr $x*3
When a $ appears in a command, Tcl treats the letters and digits following it as a
variable name, and substitutes the value of the variable in place of the name. In this
example, the actual argument received by the expr command will be 32*3 (assuming that
variable x was set as in the previous example). You can use variable substitution in any
word of any command, or even multiple times within a word:
set cmd expr
set x 11
$cmd $x*$x
Command substitution
You can also use the result of one command in an argument to another command.
This is called command substitution:
set a 44
set b [expr $a*4]
When a [ appears in a command, Tcl treats everything between it and the matching ]
as a nested Tcl command. Tcl evaluates the nested command and substitutes its result into
the enclosing command in place of the bracketed text. In the example above the second
argument of the second set command will be 176.
Double-quotes allow you to specify words that contain spaces. For example,
consider the following script:
set x 24
set y 18
set z "$x + $y is [expr $x + $y]"
After these three commands are evaluated variable z will have the value 24 + 18 is 42.
Everything between the quotes is passed to the set command as a single word. Note that (a)
command and variable substitutions are performed on the text between the quotes, and (b)
the quotes themselves are not passed to the command. If the quotes were not present, the set
command would have received 6 arguments, which would have caused an error.
Curly braces provide another way of grouping information into words. They are
different from quotes in that no substitutions are performed on the text between the curly
braces:
set z {$x + $y is [expr $x + $y]}
This command sets variable z to the value "$x + $y is [expr $x + $y]".
Control structures
As you have seen, all of the interesting features in Tcl are represented by
commands. Statements are commands, expressions are evaluated by executing commands,
control structures are commands, and procedures are commands.
Tcl commands are created in three ways. One group of commands is provided by
the Tcl interpreter itself. These commands are called builtin commands. They include all of
the commands you have seen so far and many more (see below). The builtin commands are
present in all Tcl applications.
The second group of commands is created using the Tcl extension mechanism. Tcl
provides APIs that allow you to create a new command by writing a command procedure in
C or C++ that implements the command. You then register the command procedure with
the Tcl interpreter by telling Tcl the name of the command that the procedure implements.
In the future, whenever that particular name is used for a Tcl command, Tcl will call your
command procedure to execute the command. The builtin commands are also implemented
using this same extension mechanism; their command procedures are simply part of the Tcl
library.
When Tcl is used inside an application, the application incorporates its key features
into Tcl using the extension mechanism. Thus the set of available Tcl commands varies
from application to application. There are also numerous extension packages that can be
incorporated into any Tcl application. One of the best known extensions is Tk, which
provides powerful facilities for building graphical user interfaces. Other extensions provide
object-oriented programming, database access, more graphical capabilities, and a variety of
other features. One of Tcl's greatest advantages for building integration applications is the
ease with which it can be extended to incorporate new features or communicate with other
resources.
The third group of commands consists of procedures created with the proc
command, such as the power command created above. Typically, extensions are used for
lower-level functions where C programming is convenient, and procedures are used for
higher-level functions where it is easier to write in Tcl.
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
– Single thread of control: no locking or race conditions
● Back end is C++ event scheduler
– Protocols mostly
– Fast to run, more control
• Front end is OTCL
Creating scenarios, extensions to C++ protocols
fast to write and change
Platforms
It can be employed in most unix systems(FreeBSD, Linux, Solaris) and Windows.
Source code
Most of NS2 code is in C++
Scripting language
It uses TCL as its scripting language OTcl adds object orientation to TCL.
NS programming Structure
● Create the event scheduler
● Turn on tracing
● Create network topology
● Create transport connections
● Generate traffic
● Insert errors
Tracing
● All packet trace
$ns traceall[open out.tr w]
<event> <time> <from> <to> <pkt> <size>
…
<flowid> <src> <dst> <seqno> <aseqno>
+ 0.51 0 1 cbr 500 —– 0 0.0 1.0 0 2
_ 0.51 0 1 cbr 500 —– 0 0.0 1.0 0 2
R 0.514 0 1 cbr 500 —–0 0.0 1.0 0 0
● Variable trace
set par [open output/param.tr w]
$tcp attach $par
$tcp trace cwnd_
$tcp trace maxseq_
$tcp trace rtt_
Creating topology
● Two nodes connected by a link
● Creating nodes
set n0 [$ns node]
set n1 [$ns node]
● Creating link between nodes
$ns <link_type> $n0 $n1 <bandwidth> <delay><queue-type>
$ns duplex-link$n0 $n1 1Mb 10ms DropTail
Data Sending
● Create UDP agent
set udp0 [new Agent/UDP]
$ns attach-agent $n0 $udp0
● Create CBR traffic source for feeding into UDP agent
set cbr0 [new Application/Traffic/CBR]
$cbr0 set packetSize_ 500
$cbr0 set interval_ 0.005
$cbr0 attach-agent$udp0
● Create traffic sink
set null0 [new Agent/Null]
$ns attach-agent$n1 $null0
● Connect two agents
$ns connect $udp0 $null0
● Start and stop of data
$ns at 0.5 “$cbr0 start”
$ns at 4.5 “$cbr0 stop”
Traffic on top of TCP
● FTP
set ftp [new Application/FTP]
$ftp attach-agent$tcp0
● Telnet
set telnet [new Application/Telnet]
$telnet attach-agent$tcp0
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
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:
Xgraph [options] file-name
proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam lab4.nam &
exit 0
}
$ns at 0.1 "$p1 send"
$ns at 0.2 "$p1 send"
$ns at 0.3 "$p1 send"
$ns at 0.4 "$p1 send"
$ns at 0.5 "$p1 send"
$ns at 0.6 "$p1 send"
$ns at 0.7 "$p1 send"
$ns at 0.8 "$p1 send"
$ns at 0.9 "$p1 send"
$ns at 1.0 "$p1 send"
$ns at 1.1 "$p1 send"
$ns at 1.2 "$p1 send"
$ns at 1.3 "$p1 send"
$ns at 1.4 "$p1 send"
$ns at 1.5 "$p1 send"
$ns at 1.6 "$p1 send"
$ns at 1.7 "$p1 send"
$ns at 1.8 "$p1 send"
$ns at 1.9 "$p1 send"
$ns at 2.0 "finish"
$ns run
AWK file: (Open a new editor using “vi command” and write awk file and save with
“.awk” extension)
BEGIN{
pingDrop=0;
}
{
if($1= ="d" )
{
pingDrop++;
}
}
END{
printf("Total number of ping packets dropped due to congestion is
=%d\n",pingDrop);
}
#Lan simulation
set ns [new Simulator]
#define color for data flows
$ns color 1 Blue
$ns color 2 Red
#open tracefiles
set tracefile1 [open out.tr w]
set winfile [open winfile w]
$ns trace-all $tracefile1
#open nam file
set namfile [open out.nam w]
$ns namtrace-all $namfile
#define the finish procedure
proc finish {} {
global ns tracefile1 namfile
$ns flush-trace
close $tracefile1
close $namfile
exec nam out.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]
$n1 color Red
$n1 shape box
#create links between the nodes
$ns duplex-link $n0 $n2 2Mb 10ms DropTail
$ns duplex-link $n1 $n2 2Mb 10ms DropTail
$ns simplex-link $n2 $n3 0.3Mb 100ms DropTail
$ns simplex-link $n3 $n2 0.3Mb 100ms DropTail
set lan [$ns newLan "$n3 $n4 $n5" 0.5Mb 40ms LL Queue/DropTail
MAC/Csma/Cd Channel]
#Give node position
$ns duplex-link-op $n0 $n2 orient right-down
$ns duplex-link-op $n1 $n2 orient right-up
$ns simplex-link-op $n2 $n3 orient right
$ns simplex-link-op $n3 $n2 orient left
#set queue size of link(n2-n3) to 20
$ns queue-limit $n2 $n3 20
#setup TCP connection
set tcp [new Agent/TCP/Newreno]
$ns attach-agent $n0 $tcp
set sink [new Agent/TCPSink/DelAck]
$ns attach-agent $n4 $sink
$ns connect $tcp $sink
$tcp set fid_ 1
$tcp set packet_size_ 552
#set ftp over tcp connection
set ftp [new Application/FTP]
$ftp attach-agent $tcp
#setup a UDP connection
set udp [new Agent/UDP]
$ns attach-agent $n1 $udp
set null [new Agent/Null]
$ns attach-agent $n5 $null
$ns connect $udp $null
$udp set fid_ 2
#setup a CBR over UDP connection
set cbr [new Application/Traffic/CBR]
$cbr attach-agent $udp
$cbr set type_ CBR
$cbr set packet_size_ 1000
$cbr set rate_ 0.01Mb
$cbr set random_ false
#scheduling the events
$ns at 0.1 "$cbr start"
$ns at 1.0 "$ftp start"
$ns at 124.0 "$ftp stop"
$ns at 125.5 "$cbr stop"
proc plotWindow {tcpSource file} {
global ns
set time 0.1
set now [$ns now]
set cwnd [$tcpSource set cwnd_]
puts $file "$now $cwnd"
$ns at [expr $now+$time] "plotWindow $tcpSource $file"
}
$ns at 0.1 "plotWindow $tcp $winfile"
$ns at 125.0 "finish"
$ns run
Wireless Simulation using NS-2
Simple Wireless Program in NS2 is the best way to learn about how to code in NS2.
NS2 is one of the best simulation tool used by majority of scholars today due to its
highlighted features like support for OOPs concept, C++ programming fundamentals, real
time emulation support etc. NS2 is used to simulate both wired and wireless networks; here
we have focused on wireless network simulation in NS2 due to its wide applicability.
Regarding wired simulation in NS2, refer our other articles available in this site. Here, we
have taken a simple wireless program in NS2 to explain the students about how to work
with wireless networks in NS2.
Simulating a Wireless Network in NS2
• Wireless Nodes
o A mobile node consists of network components:
Link Layer (LL)
Interface Queue (IfQ)
the MAC layer
the PHY layer: the wireless channel that the node transmit and receive
signals from
o At the beginning of a wireless simulation, we need to define the type for each of
these network components.
o Additionally, we need to define other parameters like:
the type of antenna
the radio-propagation model
the type of ad-hoc routing protocol used by mobilenodes etc.
$ns_ node-config \
-llType LL
-ifqType "Queue/DropTail/PriQueue"
-ifqLen 50
-macType Mac/802_11
-phyType "Phy/WirelessPhy"
-agentTrace ON or OFF
-routerTrace ON or OFF
-macTrace ON or OFF
-movementTrace ON or OFF
Example:
-agentTrace ON
-routerTrace ON
-macTrace OFF
-movementTrace OFF
Experiment 5 &6:
Implement and study the performance of GSM or CDMA on NS2/NS3 (Using MAC
layer) or equivalent Environment.
Architecture of LTE:
LTE parameters:
• Transmission bandwidth.
• Mobility.
• Frequency range.
• Duplexing.
• Channel bandwidth.
• Channel coding.
• MIMO.
• Multi-antenna technology.
Code:
# General Parameters
set opt(ecn) 0 ;
set opt(window) 30 ;
# Topology
set opt(type) gsm ; #type of link:
# AQM parameters
set opt(minth) 5 ;
set opt(maxth) 10 ;
set opt(adaptive) 1 ; # 1 for Adaptive RED, 0 for plain RED
#default downlink bandwidth in bps
set bwDL(gsm) 9600
#default uplink bandwidth in bps
set bwUL(gsm) 9600
#default downlink propagation delay in seconds
set propDL(gsm) .500
#default uplink propagation delay in seconds
set propUL(gsm) .500
#default buffer size in packets
set buf(gsm) 10
proc stop {} {
global nodes ns opt nf tf
$ns flush-trace
close $nf
close $tf
exec nam out1.nam &
exit 0
}
$ns at 100 "stop"
$ns run
AWK FILE
BEGIN {
PacketRcvd=0;
Throughput=0.0;
}
{
if(($1=="r") && ($5=="tcp") && ($10=4.0))
{
PacketRcvd++;
}
}
END {
Throughput=((PacketRcvd*1000*8)/(95.0*1000000));
printf("packet received:%f\n", PacketRcvd);
printf( "the throughput is:%f\n",Throughput);
}
PART B
Experiment No 7
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.
As
n-1 n-2 n-3 2 1
bn-1X + bn-2 X + bn-3 X + …b2 X + b1 X + b0
Ex: -
10001000000100001
As
16 12 5
X +X + X +1
All computations are done in modulo 2
Algorithm:-
S s
1. Given a bit string, append 0 to the end of it (the number of 0 is the same as the degree of the
generator polynomial) let B(x) be the polynomial corresponding to B.
2. Divide B(x) by some agreed on polynomial G(x) (generator polynomial) and determine the remainder
R(x). This division is to be done using Modulo 2 Division.
3. Define T(x) = B(x) –R(x)
8. Write a program to find the shortest path between vertices using bellman-ford
algorithm.
Theory
Routing algorithm is a part of network layer software which is responsible for deciding which output
line an incoming packet should be transmitted on. If the subnet uses datagram internally, this decision must
be made for every arriving data packet since the best route may have changed since last time. If the subnet
uses virtual circuits internally, routing decisions are made only when a new established route is being set
up. The latter case is sometimes called session routing, because a route remains in force for an entire user
session (e.g., login session at a terminal or a file).
Routing algorithms can be grouped into two major classes: adaptive and nonadaptive. Nonadaptive
algorithms do not base their routing decisions on measurement or estimates of current traffic and topology.
Instead, the choice of route to use to get from I to J (for all I and J) is compute in advance, offline, and
downloaded to the routers when the network ids booted. This procedure is sometime called static routing.
Adaptive algorithms, in contrast, change their routing decisions to reflect changes in the topology, and
usually the traffic as well. Adaptive algorithms differ in where they get information (e.g., locally, from
adjacent routers, or from all routers), when they change the routes (e.g., every ■T sec, when the load
changes, or when the topology changes), and what metric is used for optimization (e.g., distance, number of
hops, or estimated transit time).
Two algorithms in particular, distance vector routing and link state routing are the most popular.
Distance vector routing algorithms operate by having each router maintain a table (i.e., vector) giving the
best known distance to each destination and which line to get there. These tables are updated by
exchanging information with the neighbors.
The distance vector routing algorithm is sometimes called by other names, including the distributed
Bellman-Ford routing algorithm and the Ford-Fulkerson algorithm, after the researchers who developed it
(Bellman, 1957; and Ford and Fulkerson, 1962). It was the original ARPANET routing algorithm and was
also used in the Internet under the RIP and in early versions of DECnet and Novell’s IPX. AppleTalk and
Cisco routers use improved distance vector protocols.
In distance vector routing, each router maintains a routing table indexed by, and containing one entry
for, each router in subnet. This entry contains two parts: the preferred out going line to use for that
destination, and an estimate of the time or distance to that destination. The metric used might be number of
hops, time delay in milliseconds, total number of packets queued along the path, or something similar.
The router is assumed to know the “distance” to each of its neighbor. If the metric is hops, the distance
is just one hop. If the metric is queue length, the router simply examines each queue. If the metric is delay,
the router can measure it directly with special ECHO packets hat the receiver just time stamps and sends
back as fast as possible.
To see how fast good news propagates, consider the five node (linear) subnet of following figure, where
the delay metric is the number of hops. Suppose A is down initially and all the other routers know this. In
other words, they have all recorded the delay to A as infinity.
A B C D E A B C D E
_____ _____ _____ _____ _____ _____ _____ _____
∞ ∞ ∞ ∞ Initially 1 2 3 4 Initially
1 ∞ ∞ ∞ After 1 exchange 3 2 3 4 After 1 exchange
1 2 ∞ ∞ After 2 exchange 3 3 3 4 After 2 exchange
1 2 3 ∞ After 3 exchange 5 3 5 4 After 3 exchange
1 2 3 4 After 4 exchange 5 6 5 6 After 4 exchange
7 6 7 6 After 5 exchange
7 8 7 8 After 6 exchange
:
∞ ∞ ∞ ∞
Many ad hoc solutions to the count to infinity problem have been proposed in the literature, each one
more complicated and less useful than the one before it. The split horizon algorithm works the same way as
distance vector routing, except that the distance to X is not reported on line that packets for X are sent on
(actually, it is reported as infinity). In the initial state of right figure, for example, C tells D the truth about
distance to A but C tells B that its distance to A is infinite. Similarly, D tells the truth to E but lies to C.
Each node x begins with Dx(y), an estimate of the cost of the least-cost path from itself to node y,
for all nodes in N. Let Dx = [Dx(y): y in N] be node x’s distance vector, which is the vector of cost
estimates from x to all other nodes, y, in N. With the DV algorithm, each node x maintains the
following routing information:
• For each neighbor v, the cost c(x,v) from x to directly attached neighbor, v
• Node x’s distance vector, that is, Dx = [Dx(y): y in N], containing x’s estimate of its cost to all
destinations, y, in N
• The distance vectors of each of its neighbors, that is, Dv = [Dv(y): y in N] for each neighbor v of
x
Experiment No 9
TCP Socket
9. Using TCP/IP sockets, write a client – server program to make the client send the file name 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.
TCP is a connection-oriented protocol. This means that before the client and server can
start to send data to each other, they first need to handshake and establish a TCP connection. One
end of the TCP connection is attached to the client socket and the other end is attached to a server
socket. When creating the TCP connection, we associate with it the client socket address
(IPaddress and port number) and the server socket address (IPaddress and port number). With the
TCP connection established, when one side wants to send data to the other side, it just drops the
data into the TCP connection via its socket.
With the server process running, the client process can initiate a TCP connection to the
server. This is done in the client program by creating a TCP socket. When the client creates its
TCP socket, it specifies the address of the welcoming socket in the server, namely, the IP address
of the server host and the port number of the socket. After creating its socket, the client initiates a
three-way handshake and establishes a TCP connection with the server.
Steps:
Import net.*;
import java.io.*;
public class ContentsClient
{
public static void main( String args[ ] ) throws Exception
{
Socket sock = new Socket( "127.0.0.1", 4000);
String str;
while((str = socketRead.readLine()) != null) // reading line-by-line
{
System.out.println(str);
}
pwrite.close(); socketRead.close(); keyRead.close();
}
}
Server Side:
Steps at Server Side
1. Read the file name sent from the client using InputStream.
2. Open the file and read the contents
3. Send the contents of each line separately
Classes used:
BufferedReader, InputStream, outputStream, getOutputStream, PrintWriter, InputStream,
getInputStream
Import java.net.*;
import java.io.*;
public class ContentsServer
{
public static void main(String args[]) throws Exception
{ // establishing the connection with the server
ServerSocket sersock = new ServerSocket(4000);
System.out.println("Server ready for connection");
Socket sock = sersock.accept(); // binding with port: 4000
System.out.println("Connection is successful and wating for chatting");
String str;
while((str = contentRead.readLine()) != null) // reading line-by-line from file
{
pwrite.println(str); // sending each line to client
}
10. Write a program on datagram socket for client/server to display the messages on client
side, typed at the server side.
Using User Datagram Protocol, Applications can send data/message to the other hosts
without prior communications or channel or path. This means even if the destination host is not
available, application can send data. There is no guarantee that the data is received in the other
side. Hence it's not a reliable service.
UDP is appropriate in places where delivery of data doesn't matters during data transition.
Client Program:
import java.io.*;
import java.net.*;
class UDPClient
{
public static void main(String[] a) throws IOException
{
int i =2000;
while(true)
{
byte buf[]=new byte[1024];
DatagramSocket ds=new DatagramSocket(i);
DatagramPacket dp=new DatagramPacket(buf,buf.length);
ds.receive(dp);
String str2=new String(dp.getData(),0,dp.getLength());
System.out.println("Server:"+str2);
//ds.close();
System.out.println("**************************");
i=i+1;
}
}
}
Server Program
import java.io.*;
import java.net.*;
class UDPServer
{
public static void main(String [] a) throws IOException
{
int i =2000;
String fooString1 = new String("exit");
while(true)
{
//String ip = ;
InetAddress clientIP=InetAddress.getLocalHost();
int clientPort=i;
byte buf[]=new byte[1024];
DatagramSocket ds=new DatagramSocket();
BufferedReader dis =new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Server is Running......");
String str1=new String(dis.readLine());
if(str1.equals(fooString1))
{
ds.close();
break;
}
else
{
buf=str1.getBytes();
DatagramPacket packet=new
DatagramPacket(buf,str1.length(),clientIP,clientPort);
ds.send(packet);
i=i+1;
}
// ds.close();
}
}
}
Experiment No 11
RSA Algorithm
11. Write a program for simple RSA algorithm to encrypt and decrypt the data.
Theory
Cryptography has a long and colorful history. The message to be encrypted, known as the plaintext, are
transformed by a function that is parameterized by a key. The output of the encryption process, known as
the ciphertext, is then transmitted, often by messenger or radio. The enemy, or intruder, hears and
accurately copies down the complete ciphertext. However, unlike the intended recipient, he does not know
the decryption key and so cannot decrypt the ciphertext easily. The art of breaking ciphers is called
cryptanalysis the art of devising ciphers (cryptography) and breaking them (cryptanalysis) is collectively
known as cryptology.
There are several ways of classifying cryptographic algorithms. They are generally categorized based on
the number of keys that are employed for encryption and decryption, and further defined by their
application and use. The three types of algorithms are as follows:
1. Secret Key Cryptography (SKC): Uses a single key for both encryption and decryption. It is also
known as symmetric cryptography.
2. Public Key Cryptography (PKC): Uses one key for encryption and another for decryption. It is
also known as asymmetric cryptography.
3. Hash Functions: Uses a mathematical transformation to irreversibly "encrypt" information
Public-key cryptography has been said to be the most significant new development in cryptography.
Modern PKC was first described publicly by Stanford University professor Martin Hellman and graduate
student Whitfield Diffie in 1976. Their paper described a two-key crypto system in which two parties could
engage in a secure communication over a non-secure communications channel without having to share a
secret key.
Generic PKC employs two keys that are mathematically related although knowledge of one key does not
allow someone to easily determine the other key. One key is used to encrypt the plaintext and the other key
is used to decrypt the ciphertext. The important point here is that it does not matter which key is applied
first, but that both keys are required for the process to work. Because pair of keys is required, this approach
is also called asymmetric cryptography.
In PKC, one of the keys is designated the public key and may be advertised as widely as the owner
wants. The other key is designated the private key and is never revealed to another party. It is straight
forward to send messages under this scheme.
The RSA algorithm is named after Ron Rivest, Adi Shamir and Len Adleman, who invented it in 1977.
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.
Algorithm
1. Generate two large random primes, P and Q, of approximately equal size.
2. Compute N = P x Q
3. Compute Z = (P-1) x (Q-1).
4. Choose an integer E, 1 < E < Z, such that GCD (E, Z) = 1
5. Compute the secret exponent D, 1 < D < Z, such that E x D ≡ 1 (mod Z)
6. The public key is (N, E) and the private key is (N, D).
Note that we don't have to calculate the full value of 13 to the power 7 here. We can make use of the fact that
a = bc mod n = (b mod n).(c mod n) mod n so we can break down a potentially large number into its components
and combine the results of easier, smaller calculations to calculate the final value.
Experiment No 12
Leaky Bucket
12. Write a program for congestion control using Leaky bucket algorithm.
Theory
The congesting control algorithms are basically divided into two groups: open loop and closed loop. Open
loop solutions attempt to solve the problem by good design, in essence, to make sure it does not occur in the first
place. Once the system is up and running, midcourse corrections are not made. Open loop algorithms are further
divided into ones that act at source versus ones that act at the destination.
In contrast, closed loop solutions are based on the concept of a feedback loop if there is any congestion.
Closed loop algorithms are also divided into two sub categories: explicit feedback and implicit feedback. In
explicit feedback algorithms, packets are sent back from the point of congestion to warn the source. In
implicit algorithm, the source deduces the existence of congestion by making local observation, such as the
time needed for acknowledgment to come back.
The presence of congestion means that the load is (temporarily) greater than the resources (in part of the
system) can handle. For subnets that use virtual circuits internally, these methods can be used at the network
layer.
Another open loop method to help manage congestion is forcing the packet to be transmitted at a more
predictable rate. This approach to congestion management is widely used in ATM networks and is called
traffic shaping.
The other method is the leaky bucket algorithm. Each host is connected to the network by an interface
containing a leaky bucket, that is, a finite internal queue. If a packet arrives at the queue when it is full, the
packet is discarded. In other words, if one or more process are already queued, the new packet is
unceremoniously discarded. This arrangement can be built into the hardware interface or simulate d by the
host operating system. In fact it is nothing other than a single server queuing system with constant service
time.
The host is allowed to put one packet per clock tick onto the network. This mechanism turns an uneven
flow of packet from the user process inside the host into an even flow of packet onto the network,
smoothing out bursts and greatly reducing the chances of congestion.