Ns
Ns
Ns
Part-A
Introduction to NS-2:
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.
Tcl scripting
• Tcl is a general purpose scripting language. [Interpreter]
• Tcl runs on most of the platforms such as Unix, Windows, and Mac.
• The strength of Tcl is its simplicity.
• It is not necessary to declare a data type for variable prior to the usage.
Basics of TCL
Syntax: command arg1 arg2 arg3
Hello World!
puts stdout{Hello, World!}
Hello, World!
Variables Command Substitution
set a 5 set len [string length foobar]
set b $a set len [expr [string length foobar] + 9]
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} {
... ...
} }
Wired TCL Script Components
Create the event scheduler
Open new files & turn on the tracing
Create the nodes
Setup the links
Configure the traffic type (e.g., TCP, UDP, etc)
Set the time of traffic generation (e.g., CBR, FTP)
Terminate the simulation
NS Simulator Preliminaries.
1. Initialization and termination aspects of the ns simulator.
2. Definition of network nodes, links, queues and topology.
3. Definition of agents and of applications.
4. The nam visualization tool.
5. Tracing and random variables.
Which is thus the first line in the tcl script? 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:
#Open the Trace file set tracefile1 [open out.tr w]
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.
#Define a „finish‟ procedure
Proc finish { } {
$ns flush-trace
Close $tracefile1
Close $namfile
Exit 0
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,
$ns at 125.0 “finish”
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
$ns run
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. An example of a definition of a
link is:
$ns duplex-link $n0 $n2 10Mb 10ms DropTail
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 ―simplex-
link‖.
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).
Dept of ISE, CIT, Gubbi Page no 4
Networks Lab 2016-17
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:
#set Queue Size of link (n0-n2) to 20
The command $ns attach-agent $n0 $tcp defines the source node of the tcp connection.
The command
set sink [new Agent /TCPSink]
Defines the behavior of the destination node of TCP and assigns to it a pointer called sink.
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.
When we have several flows, we may wish to distinguish them so that we can identify them with different
colors in the visualization part. This is done by the command $tcp set fid_ 1 that assigns to the TCP connection a
flow identification of ―1‖.We shall later give the flow identification of ―2‖ to the UDP connection.
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:
Xgraph [options] file-name
Awk- An Advanced
Here, selection_criteria filters input and select lines for the action component to act upon. The
selection_criteria is enclosed within single quotes and the action within the curly braces. Both the
selection_criteria and action forms an awk program.
Example: $ awk „/manager/ {print}‟ emp.lst
Variables
Awk allows the user to use variables of there choice. You can now print a serial number, using the
variable kount, and apply it those directors drawing a salary exceeding 6700:
$ awk –F”|” „$3 == “director” && $6 > 6700 {
kount =kount+1
printf “ %3f %20s %-12s %d\n”, kount,$2,$3,$6 }‟ empn.lst
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:
proc finish { } {
global ns nf tf
$ns flush-trace # clears trace file contents
close $nf
close $tf
exec nam PA1.nam &
exit 0
}
set n0 [$ns node] # creates 3 nodes
set n2 [$ns node]
set n3 [$ns node]
AWK file: (Open a new editor using “vi command” and write awk file and save with “.awk” extension)
#immediately after BEGIN should open braces „{„
BEGIN{ c=0;}
{
if($1= ="d")
{ c++;
printf("%s\t%s\n",$5,$11);
}
}
END{ printf("The number of packets dropped =%d\n",c); }
Open vi editor and type program. Program name should have the extension “ .tcl ”
[root@localhost ~]# vi lab1.tcl
Save the program by pressing “ESC key” first, followed by “Shift and :” keys simultaneously and type “wq” and
press Enter key.
Open vi editor and type awk program. Program name should have the extension “.awk ”
[root@localhost ~]# vi lab1.awk
Save the program by pressing “ESC key” first, followed by “Shift and :” keys simultaneously and type “wq” and
press Enter key.
Run the simulation program
[root@localhost~]# ns lab1.tcl
Here “ns” indicates network simulator. We get the topology shown in the snapshot.
Now press the play button in the simulation window and the simulation will begins.
After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f lab1.awk lab1.tr
To see the trace file contents open the file as ,
[root@localhost~]# vi lab1.tr
Evaluation:
Aim: Simulate a four node point to point network with the links connected as follows: n0 – n2, n1 – n2 and n2 –
n3. Apply TCP agent between n0 – n3 and UDP agent between n1 – n3. Apply relevant applications over TCP
and UDP agents changing the parameter and determine the number of packets sent by TCP / UDP.
Program:
AWK file: (Open a new editor using “vi command” and write awk file and save with “.awk” extension)
BEGIN{
udp=0;
tcp=0;
}
{
if($1= = “r” && $5 = = “cbr”)
{
udp++;
}
else if($1 = = “r” && $5 = = “tcp”)
{ tcp++;
}
}
END{
printf(“Number of packets sent by TCP = %d\n”, tcp);
printf(“Number of packets sent by UDP=%d\n”,udp);
}
Open vi editor and type program. Program name should have the extension “ .tcl ”
[root@localhost ~]# vi lab2.tcl
Save the program by pressing “ESC key” first, followed by “Shift and :” keys simultaneously and type
“wq” and press Enter key.
Open vi editor and type awk program. Program name should have the extension “.awk ”
[root@localhost ~]# vi lab2.awk
Save the program by pressing “ESC key” first, followed by “Shift and :” keys simultaneously and type
“wq” and press Enter key.
Run the simulation program
[root@localhost~]# ns lab2.tcl
o Here “ns” indicates network simulator. We get the topology shown in the snapshot.
o Now press the play button in the simulation window and the simulation will begins.
After simulation is completed run awk file to see the output ,
[root@localhost~]# awk –f lab2.awk lab2.tr
To see the trace file contents open the file as ,
[root@localhost~]# vi lab2.tr
Topology Output
Evaluation:
Aim: Simulate the transmission of ping messages over a network topology consisting of 6 nodes and find the
number of packets dropped due to congestion.
Program:
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 "$p1 send"
$ns at 2.1 "$p1 send"
$ns at 2.2 "$p1 send"
$ns at 2.3 "$p1 send"
$ns at 2.4 "$p1 send"
$ns at 2.5 "$p1 send"
$ns at 2.6 "$p1 send"
$ns at 2.7 "$p1 send"
$ns at 2.8 "$p1 send"
$ns at 2.9 "$p1 send"
AWK file: (Open a new editor using “vi command” and write awk file and save with “.awk” extension)
BEGIN{
drop=0;
}
{
if($1= ="d" )
{
drop++;
}
}
END{
printf("Total number of %s packets dropped due to congestion =%d\n",$5,drop);
}
Topology Output
Evaluation:
Aim: Simulate an Ethernet LAN using „n‟ nodes, change error rate and data rate and compare throughput.
Program:
$ns make-lan "$n0 $n1 $n2 $n3" 100Mb 300ms LL Queue/ DropTail Mac/802_3
$ns make-lan "$n4 $n5 $n6 $n7" 100Mb 300ms LL Queue/ DropTail Mac/802_3
# set error rate. Here ErrorModel is a class and it is single word and space should not be given between
Error and Model
# lossmodel is a command and it is single word. Space should not be given between loss and model
proc finish { } {
global ns nf tf
$ns flush-trace
close $nf
close $tf
exec nam lab5.nam &
exit 0
}
AWK file: (Open a new editor using “vi command” and write awk file and save with “.awk” extension)
BEGIN{
pkt=0;
time=0;
}
{
if($1= ="r" && $3= ="9" && $4= ="7"){
pkt = pkt + $6;
time =$2;
}
}
END {
printf("throughput:%fMbps",(( pkt / time) * (8 / 1000000)));
}
Topology Output
Evaluation:
Aim: Simulate an Ethernet LAN using „n‟ nodes and set multiple traffic nodes and plot congestion window for
different source / destination.
Program:
$ns make-lan "$n0 $n1 $n2 $n3 $n4" 100Mb 100ms LL Queue/ DropTail Mac/802_3 # should come in
single line
$ns duplex-link $n4 $n5 1Mb 1ms DropTail
$tcp0 trace cwnd_ # must put underscore ( _ ) after cwnd and no space between them
$tcp2 trace cwnd_
proc finish { } {
global ns nf tf
$ns flush-trace
close $tf
close $nf
exec nam pgm7.nam &
exit 0
}
AWK file: (Open a new editor using “vi command” and write awk file and save with “.awk” extension)
cwnd:- means congestion window
BEGIN {
}
{
if($6= ="cwnd_") # don‟t leave space after writing cwnd_
printf("%f\t%f\t\n",$1,$7); # you must put \n in printf
}
END {
}
Output Graph
Evaluation:
Aim: Simulate simple ESS and with transmitting nodes in wireless LAN by simulation and determine the
performance with respect to transmission of packets.
Program:
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
Topology:
Here “M” indicates mobile nodes, “AGT” indicates Agent Trace, “RTR” indicates Router Trace
Output:
Evaluation:
With decimal calculations you can quickly check that 109 divided by 19 gives a quotient of 5 with 14 as
the remainder. But what we also see in the scheme is that every bit extra to check only costs one binary
comparison and in 50% of the cases one binary subtraction. You can easily increase the number of bits of the test
data string—for example to 56 bits if we use our example value "Lammert"—and the result can be calculated
with 56 binary comparisons and an average of 28 binary subtractions. This can be implemented in hardware
directly with only very few transistors involved. Also software algorithms can be very efficient.
All of the CRC formulas you will encounter are simply checksum algorithms based on modulo-2 binary
division where we ignore carry bits and in effect the subtraction will be equal to an exclusive or operation.
Though some differences exist in the specifics across different CRC formulas, the basic mathematical process is
always the same:
The message bits are appended with c zero bits; this augmented message is the dividend
A predetermined c+1-bit binary sequence, called the generator polynomial, is the divisor
The checksum is the c-bit remainder that results from the division operation
Table 1 lists some of the most commonly used generator polynomials for 16- and 32-bit CRCs. Remember that
the width of the divisor is always one bit wider than the remainder. So, for example, you’d use a 17-bit generator
polynomial whenever a 16-bit checksum is required.
CRC-CCITT CRC-16 CRC-32
Checksu
16 bits 16 bits 32 bits
m Width
Generator
100010000001000 110000000000001 10000010011000001000111011011
Polynomi
01 01 0111
al
Table 1. International Standard CRC Polynomials
Error detection with CRC
Consider a message represented by the polynomial M(x)
Consider a generating polynomial G(x)
This is used to generate a CRC = C(x) to be appended to M(x).
Note this G(x) is prime.
Steps:
1. Multiply M(x) by highest power in G(x). i.e. Add So much zeros to M(x).
2. Divide the result by G(x). The remainder = C(x).
Special case: This won't work if bitstring =all zeros. We don't allow such an M(x).But M(x) bitstring
= 1 will work, for example. Can divide 1101 into 1000.
3. If: x div y gives remainder c
that means: x = n y + c
Hence (x-c) = n y
(x-c) div y gives remainder 0
Here (x-c) = (x+c)
Hence (x+c) div y gives remainder 0
4.
5.
//Generator Polynomial:g(x)=x^16+x^12+x^5+1
int gp[]={1,0,0,0,1,0,0,0,0,0,0,1,0,0,0,0,1,};
int main()
{
void div();
system("clear");
printf("\nEnter the length of Data Frame :");
scanf("%d",&len);
printf("\nEnter the Message :");
for(i=0;i<len;i++)
scanf("%d",&a[i]);
1.
2.
div();
for(i=0;i<len;i++)
if(a[i]!=0)
{
printf("\nERROR in Recived Data");
return 0;
}
printf("\nData Recived is ERROR FREE");
}
void div()
{
for(i=0;i<k;i++)
{
if(a[i]==gp[0])
{
for(j=i;j<17+i;j++)
a[j]=a[j]^gp[count++];
}
count=0;
}
}
Output:
[root@localhost ]# cc prg1.c
[root@localhost ]# ./a.out
Enter the length of Data Frame :4
Enter the Message :1 0 1 1
Data to be transmitted : 1 0 1 1 1 0 1 1 0 0 0 1 0 1 1 0 1 0 1 1
1.
2.
Evaluation:
Department of ISE
Marks
Particulars Max. Marks
Obtained
Preparation 05
Performance 10
Viva-Voice 05
Result/Output 05
Total 25
Student Signature Staff Signature with
with Date Date
Figure (a) A subnet. (b) Input from A, I, H, K, and the new routing table for J.
Implementation Algorithm:
1. send my routing table to all my neighbors whenever my link table changes
2. when I get a routing table from a neighbor on port P with link metric M:
a. add L to each of the neighbor's metrics
b. for each entry (D, P', M') in the updated neighbor's table:
i. if I do not have an entry for D, add (D, P, M') to my routing table
ii. if I have an entry for D with metric M", add (D, P, M') to my routing table if M' < M"
3. if my routing table has changed, send all the new entries to all my neighbors.
Source Code:
#include<stdio.h>
#include<stdlib.h>
void rout_table();
int d[10][10],via[10][10];
int i,j,k,l,m,n,g[10][10],temp[10][10],ch,cost;
int main()
{
system("clear");
printf("enter the value of no. of nodes\n");
scanf("%d",&n);
rout_table();
for(i=0;i<n;i++)
for(j=0;j<n;j++)
temp[i][j]=g[i][j];
for(i=0;i<n;i++)
for(j=0;j<n;j++)
via[i][j]=i;
while(1)
{
for(i=0;i<n;i++)
for(j=0;j<n;j++)
if(d[i][j])
for(k=0;k<n;k++)
if(g[i][j]+g[j][k]<g[i][k])
{
g[i][k]=g[i][j]+g[j][k];
via[i][k]=j;
}
for(i=0;i<n;i++)
{
printf("table for router %c\n" ,i+97);
for(j=0;j<n;j++)
printf("%c:: %d via %c\n" ,j+97,
g[i][j],via[i][j]+97);
}
Break;
}
}
}
void rout_table()
{
printf("\nEnter the routing table : \n");
printf("\t|");
for(i=1;i<=n;i++)
printf("%c\t",i+96);
printf("\n");
for(i=0;i<=n;i++)
printf("-------");
printf("\n");
for(i=0;i<n;i++)
{
printf("%c |",i+97);
for(j=0;j<n;j++)
{
scanf("%d",&g[i][j]);
if(g[i][j]!=999)
d[i][j]=1;
}
}
}
Output:
[root@localhost ]# cc prg3.c
[root@localhost ]# ./a.out
Evaluation:
Department of ISE
Marks
Particulars Max. Marks
Obtained
Preparation 05
Performance 10
Viva-Voice 05
Result/Output 05
Total 25
Student Signature Staff Signature with
with Date Date
Socket characteristics
Sockets are characterized by their domain, type and transport protocol. Common domains are:
AF_UNIX: address format is UNIX pathname
AF_INET: address format is host and port number
Common types are:
virtual circuit: received in order transmitted and reliably
datagram: arbitrary order, unreliable
Use of sockets:
Connection–based sockets communicate client-server: the server waits for a connection from the client
Connectionless sockets are peer-to-peer: each process is symmetric.
Socket APIs
socket: creates a socket of a given domain, type, protocol (buy a phone)
bind: assigns a name to the socket (get a telephone number)
listen: specifies the number of pending connections that can be queued for a server socket. (call waiting
allowance)
accept: server accepts a connection request from a client (answer phone)
connect: client requests a connection request to a server (call)
Connection-based communication
Server performs the following actions
socket: create the socket
bind: give the address of the socket on the server
listen: specifies the maximum number of connection requests that can be pending for this process
accept: establish the connection with a specific client
send, recv: stream-based equivalents of read and write (repeated)
shutdown: end reading or writing
close: release kernel data structures
Client performs the following actions
socket: create the socket
connect: connect to a server
send, recv: (repeated)
shutdown
close
TCP-based sockets
socket API
#include<sys/types.h>
#include<sys /socket.h>
int socket(int domain, int type, int protocol) ;
Returns a file descriptor (called a socket ID) if successful, -1 otherwise. Note that the socket returns a socket
descriptor which is the same as a file descriptor.
The domain is AF_INET.
The type argument can be:
SOCK_STREAM: Establishes a virtual circuit for stream
SOCK_DGRAM: Establishes a datagram for communication
SOCK_SEQPACKET: Establishes a reliable, connection based, two way communication with maximum
message size. (This is not available on most machines.)
protocol is usually zero, so that type defines the connection within domain.
bind
#include <sys / types.h>
#include<sys / socket.h>
int bind(int sid, struct sockaddr *addrPtr, int len)
Where
sid: is the socket id
addrPtr: is a pointer to the address family dependent address structure
len: is the size of *addrPtr
Associates a socket id with an address to which other processes can connect. In internet protocol the address is
[ipNumber, portNumber]
sockaddr
For the internet family:
struct sockaddr_in {
sa_family_t sin_family; // = AF INET
in_port_t sin_port; // is a port number
struct in_addr sin_addr; // an IP address
}
listen
#include <sys / types.h>
#include <sys / socket.h>
int listen (int sid, int size) ;
Where size it the number of pending connection requests allowed (typically limited by Unix kernels to 5).
Returns the 0 on success, or -1 if failure.
accept
#include <sys / types.h>
#include <sys / socket.h>
int accept(int sid ,struct sockaddr *addrPtr , int *lenPtr )
send
#include <sys / types.h>
#include <sys / socket.h>
int send(int sid ,const char *bufferPtr ,int len ,int flag)
Send a message. Returns the number of bytes sent or -1 if failure.
(Must be a bound socket).
flag is either
0: default
MSG OOB: Out-of-band high priority communication
recv
#include <sys / types.h>
#include <sys / socket.h>
int recv ( int sid , char *bufferPtr , int len , int flags)
Receive up to len bytes in bufferPtr. Returns the number of bytes received or -1 on failure.
flags can be either
0: default
MSG OOB: out-of-bound message
MSG PEEK: look at message without removing
Shutdown
#include <sys / types.h>
#include <sys / socket.h>
int shutdown ( int sid , int how)
Disables sending (how=1 or how=2) or receiving (how=0 or how=2). Returns -1 on failure.
Connect
-this is the first of the client calls
#include <sys / types.h>
#include <sys / socket.h>
int connect ( int sid , struct sockaddr *addrPtr , int len)
Specifies the destination to form a connection with (addrPtr), and returns a 0 if successful, -1 otherwise.
Port usage
Note that the initiator of communications needs a fixed port to target communications.
This means that some ports must be reserved for these ―well known‖ ports.
Port usage:
0-1023: These ports can only be binded to by root
1024-5000: well known ports
5001-64K-1: ephemeral ports
Source Code:
Client Side:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
#include<string.h>
#define SERV_TCP_PORT 6880
#define SERV_HOST_ADDR "127.0.0.1"
int main()
{ int sockfd;
struct sockaddr_in serv_addr,cli_addr;
char filename[100],buf[1000];
int n;
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=inet_addr(SERV_HOST_ADDR);
serv_addr.sin_port=htons(SERV_TCP_PORT);
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
printf("Client:cant open stream socket\n");
else
printf("Client:stream socket opened successfully\n");
Output:
AT CLIENT SIDE
[root@localhost ]# cc tcpc.c
[root@localhost ]# ./a.out
Data Sent
File Content....
Sockets are a mechanism for exchanging data between processes. These processes can either be on the same
machine, or on different machines connected via a network. Once a socket connection is established, data can be
sent in both directions until one of the endpoints closes the connection.
I needed to use sockets for a project I was working on, so I developed and refined a few C++ classes to
encapsulate the raw socket API calls. Generally, the application requesting the data is called the client, and the
application servicing the request is called the server. I created two primary classes, ClientSocket and
ServerSocket, that the client and server could use to exchange data.
SERVER SIDE:
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
#include<string.h>
#define SERV_TCP_PORT 6880
#define SERV_HOST_ADDR "127.0.0.1"
int main()
{ int sockfd,newsockfd,clilen;
struct sockaddr_in cli_addr,serv_addr;
char filename[25],buf[1000];
int n,m=0;
int fd;
if((sockfd=socket(AF_INET,SOCK_STREAM,0))<0)
printf("server:cant open stream socket\n");
else
printf("server:stream socket opened successfully\n");
serv_addr.sin_family=AF_INET;
serv_addr.sin_addr.s_addr=htonl(INADDR_ANY);
serv_addr.sin_port=htons(SERV_TCP_PORT);
if((bind(sockfd,(struct sockaddr *)
&serv_addr,sizeof(serv_addr)))<0)
printf("server:cant bind local address\n");
else
printf("server:bound to local address\n");
listen(sockfd,5);
printf("\n SERVER : Waiting for client...\n");
for(;;)
{
clilen=sizeof(cli_addr);
newsockfd=accept(sockfd,(struct sockaddr *) &cli_addr,&clilen);
if(newsockfd<0)
printf("server:accept error\n");
else
printf("server:accepted\n");
n=read(newsockfd,filename,25);
filename[n]='\0';
printf("\n SERVER : %s is found and ready to transfer
\n",filename);
fd=open(filename,O_RDONLY);
n=read(fd,buf,1000);
buf[n]='\0';
write(newsockfd,buf,n);
printf("\n transfer success\n");
close(newsockfd);
exit(0)
} }
Output:
[root@localhost ]# cc tcps.c
[root@localhost ]# ./a.out
Received the file name : data.txt
File content sent
Evaluation:
Department of ISE
Marks
Particulars Max. Marks
Obtained
Preparation 05
Performance 10
Viva-Voice 05
Result/Output 05
Total 25
Student Signature Staff Signature with
with Date Date
Message Queues
Message queues are one of the three different types of System V IPC mechanisms. This mechanism
enables processes to send information to each other asynchronously. The word asynchronous in the present
context signifies that the sender process continues with its execution without waiting for the receiver to receive or
acknowledge the information. On the other side, the receiver does not wait if no messages are there in the queue.
The queue being referred to here is the queue implemented and maintained by the kernel.
Let us now take a look at the system calls associated with this mechanism.
a. msgget: This, in a way similar to shmget, gets a message queue identifier. The format is
int msgget(ket_t key, int msgflg);
The first argument is a unique key, which can be generated by using ftok algorithm. The second argument
is the flag which can be IPC_CREAT, IPC_PRIVATE, or one of the other valid possibilities (see the man
page); the permissions (read and/or write) are logically ORed with the flags. msgget returns an identifier
associated with the key. This identifier can be used for further processing of the message queue associated
with the identifier.
b. msgctl: This controls the operations on the message queue. The format is
int msgctl(int msqid, int cmd, struct msqid_ds *buf);
Here msqid is the message queue identifier returned by msgget. The second argument is cmd, which
indicates which action is to be taken on the message queue. The third argument is a buffer of type struct
msqid_ds. Each message queue has this structure associated with it; it is composed of records for queues to
be identified by the kernel. This structure also defines the current status of the message queue. If one of the
cmds is IPC_SET, some fields in the msqid_ds structure (pointed by the third argument) will be set to the
specified values. See the man page for the details.
c. msgsnd: This is for sending messages. The format is
int msgsnd(int msqid, struct msgbuf *msgp, size_t msgsz, int msgflg);
The first argument is the message queue identifier returned by msgget. The second argument is a structure
that the calling process allocates. A call to msgsnd appends a copy of the message pointed to by msgp to the
message queue identified by msqid. The third argument is the size of the message text within the msgbuf
structure. The fourth argument is the flag that specify one of several actions to be taken as and when a
specific situation arises.
Output:
AT SERVER SIDE
[root@localhost ]# cc prg6s.c
[root@localhost ]# ./a.out
SERVER online!
CLIENT online!
Waiting for request....SERVER: /Test.txt found!
Transfering the contents...
SERVER transfer Completed!
SERVER transfer Completed!
CLIENT SIDE:
#include<stdio.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
int main()
{ char filename[100],buf[300];
int num,num2,fl,fd,fd2;
mknod("fifo1",S_IFIFO | 0666,0);
mknod("fifo2",S_IFIFO | 0666,0);
fd=open("fifo1",O_WRONLY);
printf("CLient Online! \n CLIENT enter the path...\n\n");
scanf("%s",filename);
write(fd,filename,strlen(filename));
printf("\n waiting for reply...\n");
fd2=open("fifo2",O_RDONLY);
num2=read(fd2,buf,300);
buf[num2]='\0';
printf("\n File received ..the contents are...\n");
fputs(buf,stdout);
unlink("fifo1");
unlink("fifo2");
exit(1);
}
Output:
AT CLIENT SIDE
[root@localhost]# cc prg6c.c
[root@localhost]# ./a.out
Waiting for SERVER...
SERVER online!
CLIENT: Enter the path: /Test.txt
Wating for reply...
File recieved! Displaying the contents:
Sockets are a mechanism for exchanging data between processes. These processes can either be on the same
machine, or on different machines connected via a network. Once a socket connection is established, data can be
sent in both directions until one of the endpoints closes the connection.
I needed to use sockets for a project I was working on, so I developed and refined a few C++ classes to
encapsulate the raw socket API calls. Generally, the application requesting the data is called the client, and the
application servicing the request is called the server. I created two primary classes, C ZlientSocket and
ServerSocket, that the client and server could use to exchange data.
[root@localhost ]#
Evaluation:
Department of ISE
Marks
Particulars Max. Marks
Obtained
Preparation 05
Performance 10
Viva-Voice 05
Result/Output 05
Total 25
Student Signature Staff Signature with
with Date Date
Experiment No: 5 RSA Algorithm to Encrypt and Decrypt the Data Date:
Aim: C 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.
A very simple example of RSA encryption
This is an extremely simple example using numbers you can work out on a pocket calculator (those of
you over the age of 35 can probably even do it by hand on paper).
1. Select primes p = 11, q = 3.
2. n = pq = 11.3 = 33
phi = (p-1)(q-1) = 10.2 = 20
3. Choose e=3
Check gcd(e, p-1) = gcd(3, 10) = 1 (i.e. 3 and 10 have no common factors except 1),
and check gcd(e, q-1) = gcd(3, 2) = 1
therefore gcd(e, phi) = gcd(e, (p-1)(q-1)) = gcd(3, 20) = 1
4. Compute d such that ed ≡ 1 (mod phi)
i.e. compute d = e^-1 mod phi = 3^-1 mod 20
i.e. find a value for d such that phi divides (ed-1)
i.e. find d such that 20 divides 3d-1.
Simple testing (d = 1, 2, ...) gives d = 7
Check: ed-1 = 3.7 - 1 = 20, which is divisible by phi.
5. Public key = (n, e) = (33, 3)
Private key = (n, d) = (33, 7).
This is actually the smallest possible value for the modulus n for which the RSA algorithm works.
Now say we want to encrypt the message m = 7,
c = m^e mod n = 7^3 mod 33 = 343 mod 33 = 13.
Hence the ciphertext c = 13.
To check decryption we compute
m' = c^d mod n = 13^7 mod 33 = 7.
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.
One way of calculating m' is as follows:-
m' = 13^7 mod 33 = 13^(3+3+1) mod 33 = 13^3.13^3.13 mod 33
= (13^3 mod 33).(13^3 mod 33).(13 mod 33) mod 33
= (2197 mod 33).(2197 mod 33).(13 mod 33) mod 33
= 19.19.13 mod 33 = 4693 mod 33
= 7.
Now if we calculate the cipher text c for all the possible values of m (0 to 32), we get
m 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
c 0 1 8 27 31 26 18 13 17 3 10 11 12 19 5 9 4
m 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
c 29 24 28 14 21 22 23 30 16 20 15 7 2 6 25 32
Note that all 33 values of m (0 to 32) map to a unique code c in the same range in a sort of random
manner. In this case we have nine values of m that map to the same value of c - these are known as unconcealed
messages. m = 0 and 1 will always do this for any N, no matter how large. But in practice, higher values shouldn't
be a problem when we use large values for N.
If we wanted to use this system to keep secrets, we could let A=2, B=3, ..., Z=27. (We specifically avoid 0
and 1 here for the reason given above). Thus the plaintext message "HELLOWORLD" would be represented by
the set of integers m1, m2, ...
{9,6,13,13,16,24,16,19,13,5}
Using our table above, we obtain ciphertext integers c1, c2, ...
{3,18,19,19,4,30,4,28,19,26}
Note that this example is no more secure than using a simple Caesar substitution cipher, but it serves to
illustrate a simple example of the mechanics of RSA encryption.
Remember that calculating m^e mod n is easy, but calculating the inverse c^-e mod n is very difficult,
well, for large n's anyway. However, if we can factor n into its prime factors p and q, the solution becomes easy
again, even for large n's. Obviously, if we can get hold of the secret exponent d, the solution is easy, too.
for(i=2;i<phi;i++)
if(gcd(i,phi)==1) break;
e=i;
for(i=2;i<phi;i++)
if((e*i-1)%phi==0)break;
d=i;
for(i=0;i<strlen(message);i++)
nummes[i]=message[i]-96;
nofelem=strlen(message);
for(i=0;i<nofelem;i++)
{
encrypted[i]=1;
for(j=0;j<e;j++)
encrypted[i] =(encrypted[i]*nummes[i])%n;
}
printf("\n Encrypted message\n");
for(i=0;i<nofelem;i++)
{
printf(" %ld ",encrypted[i]);
printf("%c",(char)(encrypted[i])+96);
}
for(i=0;i<nofelem;i++)
{
decrypted[i]=1;
for(j=0;j<d;j++)
decrypted[i]=(decrypted[i]*encrypted[i])%n;
}
int main()
{ char msg[];
clrscr();
printf("Enter The Message To Be Encrypted\n");
scanf("%s",msg);
rsa(msg);
return 0;
}
[root@localhost ]# cc prg7.c
[root@localhost ]# ./a.out
Evaluation:
Department of ISE
Marks
Particulars Max. Marks
Obtained
Preparation 05
Performance 10
Viva-Voice 05
Result/Output 05
Total 25
Student Signature Staff Signature with
with Date Date
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 paclet from Queue
6. End
Source Code:
#include<stdio.h>
#include<strings.h>
#include<stdio.h>
int min(int x,int y)
{
if(x<y)
return x;
else
return y;
}
int main()
{
int drop=0,mini,nsec,cap,count=0,i,inp[25],process;
syste("clear");
printf("Enter The Bucket Size\n");
scanf("%d",&cap);
printf("Enter The Operation Rate\n");
scanf("%d",&process);
printf("Enter The No. Of Seconds You Want To Stimulate\n");
scanf("%d",&nsec);
for(i=0;i<nsec;i++)
{
printf("Enter The Size Of The Packet Entering At %dsec\n",i+1);
scanf("%d",&inp[i]);
}
printf("\nSecond|Packet Recieved|Packet Sent|PacketLeft|Packet Dropped|\n");
printf("--------------------------------------------------------------\n");
for(i=0;i<nsec;i++)
{
count+=inp[i];
if(count>cap)
{
drop=count-cap;
count=cap;
}
printf("%d",i+1);
printf("\t%d",inp[i]);
mini=min(count,process);
printf("\t\t%d",mini);
count=count-mini;
printf("\t\t%d",count);
printf("\t\t%d\n",drop);
drop=0;
}
for(;count!=0;i++)
{
if(count>cap)
{
drop=count-cap;
count=cap;
}
printf("%d",i+1);
printf("\t0");
mini=min(count,process);
printf("\t\t%d",mini);
count=count-mini;
printf("\t\t%d",count);
printf("\t\t%d\n",drop);
}
}
Output:
Compile and run
$ cc –o Congestion Congestion.c
$ ./Congestion
Enter The Bucket Size
5
Enter The Operation Rate
2
Enter The No. Of Seconds You Want To Stimulate
3
Enter The Size Of The Packet Entering At 1 sec
5
Enter The Size Of The Packet Entering At 1 sec
4
Evaluation:
Department of ISE
Marks
Particulars Max. Marks
Obtained
Preparation 05
Performance 10
Viva-Voice 05
Result/Output 05
Total 25
Student Signature Staff Signature with
with Date Date
REFERENCE