Professional Documents
Culture Documents
Course Outcome
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
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.
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)
# <http://wushoupong.googlepages.com/nsg>
#===================================
#===================================
#===================================
# Initialization
#===================================
#Create a ns simulator
#===================================
# Nodes Definition
#===================================
#Create 3 nodes
# Links Definition
#===================================
#===================================
# Agents Definition
#===================================
#===================================
# Applications Definition
#===================================
#===================================
# Termination
#===================================
#Define a 'finish' procedure
proc finish {} {
$ns flush-trace
close $tracefile
close $namfile
exit 0
$ns run
RESULT
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
EXPECTED OUTPUT
PROGRAM (2)
#Create a simulator object
set ns [new Simulator]
#Open a trace file
proc finish {} {
global ns nf nd
$ns flush-trace
close $nf
close $nd
exit 0
#Create two ping agents and attach them to the nodes n0 and n2
#Schedule events
$ns run
RESULT
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]
#Finish Procedure
proc Finish {} {
$ns flush-trace
close $ntrace
close $namfile
exit 0
global ns
#Create 6 nodes
set lan [$ns newLan "$n(3) $n(4) $n(5)" 0.5Mb 40ms LL Queue/DropTail MAC/802_3 Channel]
#Setup queue between n(2) and n(3) and monitor the queue
#Schedule Events
$ns run
RESULT
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
EXPECTED OUTPUT
#===================================
# 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
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
#===================================
# 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
#===================================
# 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
$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
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
EXPECTED OUTPUT
#===================================
# Simulation parameters setup
#===================================
set val(chan) Channel/WirelessChannel ;# channel type
set val(prop) Propagation/TwoRayGround ;# radio-propagation model
#===================================
# Initialization
#===================================
#Create a ns simulator
set ns [new Simulator]
#===================================
# 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 \
-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
#===================================
# 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"
#===================================
# 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
RESULT
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
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);
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
PART B
STEPS FOR EXECUTION OF PROGRAMS
1. Start Eclipse
2. Create a new java project
3. Create a new java class
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.
INPUT
a) Enter the Data word
b) Enter the position where error has to be inserted
EXPECTED OUTPUT
PROGRAM: CRC
package crcsender;
import java.util.Scanner;
//************************ Choice 1: Check for Validity 2:Induce error and cross check
***************//
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");
}
}
RESULT
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.
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.
package bellmanford;
import java.util.Scanner;
{
private int distances[];
{
this.numberofvertices = numberofvertices;
}
public void BellmanFordEvaluation(int source, int adjacencymatrix[][])
distances[node] = MAX_VALUE;
}
distances[source] = 0;
{
for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++)
{
for (int destinationnode = 1; destinationnode <= numberofvertices; destinationnode++)
{
if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE)
+ adjacencymatrix[sourcenode][destinationnode])
distances[destinationnode] = distances[sourcenode]
+ adjacencymatrix[sourcenode][destinationnode];
}
for (int sourcenode = 1; sourcenode <= numberofvertices; sourcenode++)
{
if (adjacencymatrix[sourcenode][destinationnode] != MAX_VALUE)
+ adjacencymatrix[sourcenode][destinationnode])
int numberofvertices = 0;
int source;
adjacencymatrix[sourcenode][destinationnode] = scanner.nextInt();
if (sourcenode == destinationnode)
adjacencymatrix[sourcenode][destinationnode] = 0;
continue;
if (adjacencymatrix[sourcenode][destinationnode] == 0)
adjacencymatrix[sourcenode][destinationnode] = MAX_VALUE;
bellmanford.BellmanFordEvaluation(source, adjacencymatrix);
scanner.close();
RESULT
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
};
// 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
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
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}
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 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();
package server;
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;
RESULT:
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
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:
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");
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);
RESULT
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:
2)Compute modulus n = pq
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.
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) ).
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
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);
RESULT
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)).
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
/**
*
* @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