Computer Networks Lab Manual: 6 Semester, B.E
Computer Networks Lab Manual: 6 Semester, B.E
Computer Networks Lab Manual: 6 Semester, B.E
Computer Networks
Lab Manual
6th Semester, B.E.
Submitted By:
Ravi B, Lecturer, Dept. of CSE.
Department of Computer Science and Engineering
Network Lab CS602
LESSON PLAN
Prerequisite:
Objectives:
To provide a good understanding of the salient features of network Programming. Students are
expected to understand the network concept in detail and to program using C/C++ programming
language.
Every laboratory sessions begins SHARP at the specified time in the schedule.
Each lab session is two hours long. Students are advised to bring their record and observation
books.
Strict discipline should be maintained throughout the lab.
Punctuality should be followed by each and every student.
Food, drinks and cell phone are not allowed inside the laboratory
Method of Assessment:
Writing Algorithms - 10
Program Execution - 30
Viva Voce - 10
Department of Computer Science and Engineering
Network Lab CS602
List of Experiments
Note: Student is required to solve one problem from PART-A and one problem from PART-B.
The following experiments shall be conducted using either NS2/OPNET or any other simulators.
1. Simulate a 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. Simulate a four node point-to-point network, and connect the links as follows: n0-n2, n1-n2
and n2-n3. Apply TCP agent between n0-n3 and UDP n1-n3. Apply relevant applications over
TCP and UDP agents changing the parameter and determine the number of packets by
TCP/UDP.
3. Simulate the different types of Internet traffic such as FTP a TELNET over a network and
analyze the throughput.
4. Simulate the transmission of ping messaged over a network topology consisting of 6 nodes and
find the number of packets dropped due to congestion.
5. Simulate an Ethernet LAN using N-nodes (6-10), change error rate and data rate and compare
the throughput.
6. Simulate an Ethernet LAN using N nodes and set multiple traffic nodes and determine collision
across different nodes.
7. Simulate an Ethernet LAN using N nodes and set multiple traffic nodes and plot congestion
window for different source/destination.
8. Simulate simple ESS and with transmitting nodes in wire-less LAN by simulation and
determine the performance with respect to transmission of packets.
PART B
The following experiments shall be conducted using C/C++.
1. Write a program for error detecting code using CRC-CCITT (16-bits).
2. Write a program for frame sorting technique used in buffers.
3. Write a program for distance vector algorithm to find suitable path for transmission.
4. 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.
5. Using UDP SOCKETS, write a client-server program to make the client sending two numbers
and an operator, and server responding with the result. Display the result and appropriate
messages for invalid inputs at the client side.
6. .Write a program for Hamming Code generation for error detection and correction.
7. Write a program for simple RSA algorithm to encrypt and decrypt the data
8. Write a program for congestion control using Leaky bucket algorithm.
Department of Computer Science and Engineering
Network Lab CS602
Part A Experiments
1. Overview of NS-2
1.2 Downloading/Installing ns
You can download the package from http://www.isi.edu/nsnam/ns/ns-build.html. There are two ways
to build ns: from the various packages or ‘all-in-one’ package. For simplicity, it is recommended to
start with the ‘all-in-one’ package. Please refer http://www.isi.edu/nsnam/ns/ns-problems.html for any
installation problems.
1.3 Starting ns
You start ns with the command 'ns <tclscript>' (assuming that you are in the directory with the ns
executable, or that your path points to that directory), where '<tclscript>' is the name of a Tcl (Tool
Command Language) script file which defines the simulation scenario (i.e. the topology and the
events). You can also just start ns without any arguments and enter the Tcl commands in the Tcl shell,
but that is definitely less comfortable.
Another major component of NS besides network objects is the event scheduler. An event in NS is a
packet ID that is unique for a packet with scheduled time and the pointer to an object that handles the
event. The event scheduler in NS-2 performs the following tasks:
Organizes the simulation timer.
Fires events in the event queue.
Invokes network components in the simulation.
Depending on the user’s purpose for an OTcl simulation script, simulation results are stored as trace
files, which can be loaded for analysis by an external application:
1. A NAM trace file (file.nam) for use with the Network Animator Tool
2. A Trace file (file.tr) for use with XGraph or TraceGraph [11].
Department of Computer Science and Engineering
Network Lab CS602
TclCL is the language used to provide a linkage between C++ and OTcl. Toolkit Command Language
(Tcl/OTcl) scripts are written to set up/configure network topologies. TclCL provides linkage for class
hierarchy, object instantiation, variable binding and command dispatching. OTcl is used for periodic
or triggered events.
1.8 XGraph
XGraph is an X-Windows application that includes:
Interactive plotting and graphing
Animation and derivatives
To use XGraph in NS-2 the executable can be called within a TCL Script. This will then load a graph
displaying the information visually displaying the information of the trace file produced from the
simulation.
Department of Computer Science and Engineering
Network Lab CS602
1.9 TraceGraph
TraceGraph is a trace file analyzer that runs under Windows, Linux and UNIX systems and requires
Mat lab 6.0 or higher.
TraceGraph supports the following trace file formats.
Wired
Satellite
Wireless
In NS-2, the network is constructed using nodes which are connected using links. Events are scheduled
to pass between nodes through the links. Nodes and links can have various properties associated with
them. Agents can be associated with nodes and they are responsible for generating different packets
(e.g. TCP agent or UDP agent). The traffic source is an application which is associated with a
particular agent (e.g. ping application).
Now we open a file for writing that is going to be used for the nam trace data.
The first line opens the file 'out.nam' for writing and gives it the file handle 'nf'. In the second line we
tell the simulator object that we created above to write all simulation data that is going to be relevant
for nam into this file. The next step is to add a 'finish' procedure that closes the trace file and starts
nam.
proc finish {} {
global ns nf
$ns flush-trace
close $nf
exec nam out.nam &
exit 0
}
A new node object is created with the command '$ns node'. The above code creates two nodes and
assigns them to the handles 'n0' and 'n1'. The next line connects the two nodes.
This line tells the simulator object to connect the nodes n0 and n1 with a duplex link with the
bandwidth 1Megabit, a delay of 10ms and a DropTail queue.
Now you can save your file and start the script with 'ns example1.tcl'. nam will be started
automatically and you should see an output that resembles the picture below.
Department of Computer Science and Engineering
Network Lab CS602
The next step is to send some data from node n0 to node n1. In ns, data is always being sent from one
'agent' to another. So the next step is to create an agent object that sends data from node n0, and
another agent object that receives the data on node n1.
These lines create a UDP agent and attach it to the node n0, then attach a CBR traffic generator to the
UDP agent. CBR stands for 'constant bit rate'. Line 7 and 8 should be self-explaining. The packet Size
is being set to 500 bytes and a packet will be sent every 0.005 seconds (i.e. 200 packets per second).
The next lines create a Null agent which acts as traffic sink and attach it to node n1.
And now we have to tell the CBR agent when to send data and when to stop sending. It's probably best
to put the following lines just before the line '$ns at 5.0 "finish"'.
$ns at 0.5 "$cbr0 start"
$ns at 4.5 "$cbr0 stop"
Now you can save the file and start the simulation again. When you click on the 'play' button in the
nam window, you will see that after 0.5 simulation seconds, node 0 starts sending data packets to node
1. You might want to slow nam down then with the 'Step' slider.
Department of Computer Science and Engineering
Network Lab CS602
Now you can add the following piece of code to your Tcl script, preferably at the beginning after the
simulator object has been created, since this is a part of the simulator setup.
This code allows you to set different colors for each flow id.
You can add the following line to your code to monitor the queue for the link from n2 to n3.
You can see the packets in the queue now, and after a while you can even see how the packets are
being dropped, though (at least on my system, I guess it might be different in later or earlier releases)
only blue packets are being dropped. But you can't really expect too much 'fairness' from a simple
Drop Tail queue. So let's try to improve the queuing by using a SFQ (stochastic fair queuing) queue
for the link from n2 to n3. Change the link definition for the link between n2 and n3 to the following
line.
$ns duplex-link $n3 $n2 1Mb 10ms SFQ
The queuing should be 'fair' now. The same amount of blue and red packets should be dropped.
Experiment No. 1
Department of Computer Science and Engineering
Network Lab CS602
Problem Statement:
Simulate a 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.
#File Name: ns_exp1.tcl
#Description: Simulating simple three nodes point-to-point network
##################################################################
#Create Nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
Experiment No. 2
Problem Statement:
Simulate a four node point-to-point network, and connect the links as follows: n0-n2, n1-n2 and n2-n3.
Apply TCP agent between n0-n3 and UDP n1-n3. Apply relevant applications over TCP and UDP
agents changing the parameter and determine the number of packets by TCP/UDP.
#Create Nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
Department of Computer Science and Engineering
Network Lab CS602
NAM output:
Department of Computer Science and Engineering
Network Lab CS602
Experiment No. 3
Problem Statement:
Simulate the different types of Internet traffic such as FTP a TELNET over a network and analyze the
throughput.
#File Name: ns_exp3.tcl
#Description: Simulating different types of Internet traffic
############################################################
#Create Nodes
set n0 [$ns node]
set n1 [$ns node]
set n2 [$ns node]
set n3 [$ns node]
Department of Computer Science and Engineering
Network Lab CS602
#Create Links between Nodes
$ns duplex-link $n0 $n2 1Mb 10ms DropTail
$ns duplex-link $n1 $n2 1Mb 10ms DropTail
$ns duplex-link $n2 $n3 1Mb 10ms DropTail
NAM output
Department of Computer Science and Engineering
Network Lab CS602
Experiment No. 4
Problem Statement:
Simulate the transmission of ping messaged over a network topology consisting of 3-6 nodes and find
the number of packets dropped due to congestion.
#File Name: ns_exp4.tcl
#Description: transmission of ping messaged over a network topology
###################################################################
#Create two ping agents and attach them to the nodes n0 and n2
set p0 [new Agent/Ping]
$ns attach-agent $n0 $p0
#Schedule events
$ns at 0.2 "$p0 send"
$ns at 0.4 "$p1 send"
$ns at 0.6 "$p0 send"
$ns at 0.6 "$p1 send"
$ns at 1.0 "finish"
NAM output:
Experiment No. 5
Problem Statement:
Department of Computer Science and Engineering
Network Lab CS602
Simulate an Ethernet LAN using N-nodes (6-10), change error rate and data rate and compare the
throughput.
#File Name: ns_exp5.tcl
#Description: Simulate an Ethernet LAN using N-nodes (6 10)
######################################################################
#Create 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]
set n6 [$ns node]
set n7 [$ns node]
set n8 [$ns node]
set n9 [$ns node]
set n10 [$ns node]
NAM output:
Experiment No. 6
Department of Computer Science and Engineering
Network Lab CS602
Problem Statement:
Simulate an Ethernet LAN using N nodes and set multiple traffic nodes and determine collision across
different nodes.
#File Name: ns_exp6.tcl
#Description: Simulate an Ethernet LAN and set multiple traffic nodes
######################################################################
#Create 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]
set n6 [$ns node]
set n7 [$ns node]
set n8 [$ns node]
set n9 [$ns node]
Experiment No. 7
Problem Statement:
Department of Computer Science and Engineering
Network Lab CS602
Simulate an Ethernet LAN using N nodes and set multiple traffic nodes and plot congestion window
for different source/destination.
#File Name: ns_exp7.tcl
#Description: Simulate an Ethernet LAN using N nodes and set multiple traffic
nodes and plot congestion window for different source/destination.
###############################################################################
#Create 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]
set n6 [$ns node]
set n7 [$ns node]
set n8 [$ns node]
set n9 [$ns node]
Experiment No. 8
Problem Statement:
Department of Computer Science and Engineering
Network Lab CS602
Simulate simple ESS and with transmitting nodes in wire-less LAN by simulation and determine the
performance with respect to transmission of packets using NCTUNS
1. Click on “access point”. Goto wireless interface and tick on “show transmission range and
then click OK.
2. Double click on Router -> Node Editor and then
Left stack -> throughput of Incoming packets
Right stack -> throughput of Outgoing packets
3. Select mobile hosts and access points then click on.
Tools -> WLAN mobile nodes-> WLAN Generate infrastructure.
Subnet ID: Port number of router (2)
Gateway ID: IP address of router
4. Mobile Host 1
ttcp –t –u –s –p 3000 1.0.1.1
5. Mobile Host 1
ttcp –t –u –s –p 3001 1.0.1.1
6. Host(Receiver)
ttcp –r –u –s –p 3000
ttcp –r –u –s –p 3001
7. Run and then play to plot the graph.
Part B Programs
Experiment No. 1
Department of Computer Science and Engineering
Network Lab CS602
Problem Statement:
Write a program for error detecting code using CRC-CCITT (16-bits).
Theory:
It does error checking via polynomial division. In general, a bit string can be represented using a
polynomial. Ex: 10010101110 can be represented as X10 + X7 + X5 + X3 + X2 + X. All computations are done
in modulo 2. The algorithm uses G(x) = X16+X12+X5 +1 as the generator polynomial which used in HDLC,
X.25, V.41, XMODEM, Bluetooth, SD and many others.
Algorithm:
1. Given a bit string, append 0S to the end of it (the number of 0s 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), (T(x)/G(x) => remainder 0)
4. Transmit T, the bit string corresponding to T(x).
5. Let T’ represent the bit stream the receiver gets and T’(x) the associated polynomial. The receiver
divides T’(x) by G(x). If there is a 0 remainder, the receiver concludes T = T’ and no error occurred
otherwise, the receiver concludes an error occurred and requires a retransmission.
/**************************************************************************
* File Name : crc.c
*
* Description :Program for error detecting code using CRC-CCITT (16-bits).
***************************************************************************/
#include<stdio.h>
#define MAX_SIZE 20
void compute_crc()
{
int i,j;
int lmb; //corresponds to right most bit of the shiftt-register circuit.
for(j=0;j<(n+16);j++)
{
lmb=r[15].bit;
r[0].bit=input[j];
for(i=15;i>=0;i--)
printf("%d ",r[i].bit);
for(i=n,j=15;j>=0;i++,j--)
input[i]=r[j].bit;
}
Department of Computer Science and Engineering
Network Lab CS602
int check_err()
{
int i;
for(i=15;i>=0;i--)
{
if(r[i].bit != 0)
{
return i;
}
}
return 0;
}
void read_input()
{
int i;
printf("\nEnter the number of bits in the input:\n");
scanf("%d",&n);
for(i=n;i<(n+16);i++)
input[i]=0;
}
int main()
{
int i;
read_input();
printf("\n\nAt sender:\n\n");
compute_crc();
printf("\n\nAt receiver:\n\n");
printf("\nEnter the received data \n");
for(i=0;i<(n+16);i++)
scanf("%d", &input[i]);
// compute CRC
compute_crc();
return 0;
}
Experiment No. 2
Problem Statement:
Write a program for frame sorting technique used in buffers.
Theory:
The data link layer divides the stream of bits received from the network layer into manageable data
units called frames. If frames are to be distributed to different systems on the network, the Data link
layer adds a header to the frame to define the sender and/or receiver of the frame. Each Data link layer
has its own frame format. One of the fields defined in the format is the maximum size of the data field.
In other words, when datagram is encapsulated in a frame, the total size of the datagram must be less
than this maximum size, which is defined by restriction imposed by the hardware and software used in
the network.
The value of MTU differs from one physical network to another In order to make IP protocol
portable/independent of the physical network, the packagers decided to make the maximum length of
Department of Computer Science and Engineering
Network Lab CS602
the IP datagram equal to the largest Maximum Transfer Unit (MTU) defined so far. However for other
physical networks we must divide the datagrams to make it possible to pass through these networks.
This is called fragmentation. When a datagram is fragmented, each fragmented has its own header. A
fragmented datagram may itself be fragmented if it encounters a network with an even smaller MTU.
In another words, a datagram may be fragmented several times before it reached the final destination
and also, the datagrams referred to as (frames in Data link layer) may arrives out of order at
destination. Hence sorting of frames need to be done at the destination to recover the original data.
The following program simulates the frame sorting technique used in buffers.
Algorithm
1. Read a message from the keyboard
2. Divide the message into fixed size packets. Include sequence number and other information in
each packet.
3. Shuffle the packets (to generate out of order packets )
4. Order the packets based on sequence numbers
5. Display the ordered packets.
/**************************************************************************
* File Name : FrameSort.c
*
* Description : A program for frame sorting technique used in buffers
***************************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#define DATA_SZ 3
return NoOfPacket;
}
free(Status);
}
sortframes(NoOfPacket);
int main()
{
char msg[25];
int NoOfPacket;
printf("\nEnter The message to be Transmitted :\n");
scanf("%[^\n]", msg);
NoOfPacket = divide(msg);
shuffle(NoOfPacket);
receive(NoOfPacket);
free(readdata);
free(transdata);
return 0;
}
Department of Computer Science and Engineering
Network Lab CS602
Experiment No. 3
Problem Statement:
Write a program for Distance Vector Algorithm to find suitable path for transmission.
Theory:
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. 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.
Algorithm:
1. Read the initial routing table. The initial routing table for each router consists of the distances
to each of its neighbours. Distance is assumed to be infinity if there is no direct path.
2. To build the final routing table, each router communicates with each of its neighbours to
update the routing table. The basic principle here is as follows:
Consider a node X that is interested in routing to destination Y via its directly attached
neighbour Z. Node X's distance table entry, Dx(Y,Z) is the sum of the cost of the direct link
between X and Z, c(X,Z), plus neighbour Z's currently known minimum cost path from itself
(Z) to Y. That is:
Dx(Y, Z) = c(X, Z) + minw{Dz(Y, w)}
The minw term is taken over all of Z's directly attached neighbours (including X)
Department of Computer Science and Engineering
Network Lab CS602
/**************************************************************************
* File Name : DistVect.c
*
* Description : A program for distance vector algorithm to find suitable
path for transmission.
***************************************************************************/
#include<stdio.h>
struct
{
int cost;
int via;
}routeTable[10][10];
for(j=0;j<n;j++)
{
for(k=0;k<n && j!=i;k++)
{
}
Department of Computer Science and Engineering
Network Lab CS602
// function to find shortest path between 2 routers
void find_path(int i,int j)
{
printf("%c",'A' + i);
if(i != j)
{
printf(" --> ");
find_path(routeTable[i][j].via,j);
}
}
printf("Enter the initial routing table (if no direct node, enter 999):\n");
for(i=0;i<n;i++)
{
printf("\nRouting table for %c:\n",'A' + i);
for(j=0;j<n;j++)
{
if(i==j)
routeTable[i][j].cost=0;
else
{
printf("--> %c:",'A' + j);
scanf("%d",&routeTable[i][j].cost);
}
if(routeTable[i][j].cost != INFINITY)
routeTable[i][j].via=j;
else
routeTable[i][j].via=INFINITY;
}
}
}
Department of Computer Science and Engineering
Network Lab CS602
// main function
int main()
{
int src,dst,i;
int opt;
do
{
printf("\nEnter the Source node(0 to %d): ",n-1);
scanf("%d",&src);
printf("Enter the Destination node(0 to %d):",n-1);
scanf("%d",&dst);
return 0;
}
Department of Computer Science and Engineering
Network Lab CS602
Experiment No. 4
Problem Statement:
Using TCP 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.
Theory:
A socket allows an application to "plug in" to the network and communicate with other applications
that are also plugged in to the same network. Information written to the socket by an application on
one machine can be read by an application on a different machine, and vice versa. Sockets come in
different flavors, corresponding to different underlying protocol families and different stacks of
protocols within a family. we deal only with the TCP/IP protocol family. The main flavors of sockets
in the TCP/IP family are stream sockets and datagram sockets. Stream sockets use TCP as the end-to-
end protocol (with IP underneath) and thus provide a reliable byte-stream service. Datagram sockets
use UDP (again, with IP underneath) and thus provide a best-effort datagram service that applications
can use to send individual messages up to about 65,500 bytes in length.
A socket using the TCP/IP protocol family is uniquely identified by an Internet address, an end-to-end
protocol (TCP or UDP), and a port number. When a socket is first created, it has an associated
protocol but no Internet address or port number. Until a socket is bound to a port number, it cannot
receive messages from a remote application.
#include<stdio.h>
#include<netdb.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<stdlib.h>
#include<string.h>
if (argc==2)
host = argv[1];
else
{
fprintf(stderr, "usage: client host\n");
exit(1);
}
printf("Enter the file name (type stop to close the SERVER) :\n");
scanf("%s",sbuf);
write(sd,sbuf,BUF_SIZE);
printf("Content of the file: \n");
while(n=read(sd,rbuf,BUF_SIZE)>0)
printf("%s",rbuf);
close(sd);
return(0);
}
/**************************************************************************
* File Name : tcpServer.c
*
* Description : Server program using tcp sockets to transfer the contents of
the requested file
***************************************************************************/
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<string.h>
#include<stdlib.h>
#include<fcntl.h>
int main()
{
int fd; // file descriptor
int sd,new_sd; // socket descriptors
int client_len;
struct sockaddr_in server,client;
char n,rbuf[BUF_SIZE],buf[BUF_SIZE]; // buffer variables
while(1)
{
client_len=sizeof(client);
printf("Waiting for connection...\n");
if ((new_sd = accept(sd,(struct sockaddr *)&client,&client_len))< 0)
{
perror("Server : accept error");
exit(1);
}
printf("Connected...\n");
n=read(new_sd,buf,BUF_SIZE);
if(strcmp(buf,"stop") == 0)
{
printf("Server is closed");
break;
}
fd=open(buf,O_RDONLY);
if(fd == -1)
printf("File %s does not exists\n",buf);
else
{
while(n=read(fd,rbuf,BUF_SIZE)>0)
{
write(new_sd,rbuf,BUF_SIZE);
}
printf("File %s content sent...\n",buf);
}
close(new_sd);
close(fd);
}
close(sd);
return(0);
}
Department of Computer Science and Engineering
Network Lab CS602
Experiment No. 5
Problem Statement:
Using UDP SOCKETS, write a client-server program to make the client sending two numbers and an
operator, and server responding with the result. Display the result and appropriate messages for invalid
inputs at the client side.
Theory: Refer to the Experiment No. 4
Algorithm (Client Side)
1. Start.
2. Create a socket using socket () system call.
3. Connect the socket to the address of the server using connect () system call.
4. Read two numbers and an operator, and them using sendto () system call.
5. Receive the result sent by server using recvfrom () system call.
6. Stop.
Algorithm (Server Side)
1. Start.
2. Create a socket using socket () system call.
3. Bind the socket to an address using bind () system call.
4. Listen to the connection using listen () system call.
5. Accept connection using accept ()
6. Receive the numbers and operator. Send the result to the client.
7. Stop.
Client/Server communication using TCP socket
Department of Computer Science and Engineering
Network Lab CS602
/**************************************************************************
* File Name : udpClient.c
*
* Description : UDP Client
***************************************************************************/
#include <stdio.h>
#include <stdio_ext.h>
#include <string.h>
#include <sys/time.h>
#include <netdb.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <string.h>
int i, j;
int opt =1;
float n1,n2;
char op;
pname = argv[0];
argc--;
argv++;
if (argc > 0)
{
host = *argv;
if (--argc > 0)
port = atoi(*++argv); // port number
}
else
{
// must specify server address
server_len = sizeof(server);
while(opt == 1)
{
printf("\n Enter operator(+,-,/,*):");
scanf("%c",&op);
printf("\n Enter first number:");
scanf("%f", &n1);
printf("\n Enter second number:");
scanf("%f", &n2);
sprintf (sbuf, "%f%c%f", n1,op, n2);
close(sd);
return(0);
}
/**************************************************************************
* File Name : udpServer.c
*
* Description : UDP server to perform arithmetic operarion and send the result.
***************************************************************************/
#include <stdio.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
switch(argc)
{
case 1:
port = SERVER_UDP_PORT;
break;
case 2:
port = atoi(argv[1]);
break;
default:
fprintf(stderr, "Usage: %s [port]\n", argv[0]);
exit(1);
}
printf("waiting .. .");
client_len = sizeof(client);
while (1)
{
dv_flg=0;
Experiment No. 6
Problem Statement:
Write a program for Hamming Code generation for error detection and correction
Theory:
Hamming codes (Richard Hamming, 1950) are used for detecting and correcting single bit errors in
transmitted data. This requires that 3 parity bits (check bits) be transmitted with every 4 data bits. The
algorithm is called A(7, 4) code, because it requires seven bits to encode 4 bits of data.
Algorithm (encoding)
1. Index (k+ r) bits starting from 1. E.g . bit 1, 2, 3, 4, 5, etc.
2. Write the bit position numbers in binary. i.e. 1, 10, 11, 100, 101, etc.
3. All bit positions that are powers of two are parity bits.
4. All other bit positions are data bits.
5. Each data bit is included in a unique set of 2 or more parity bits, as determined by the
binary form of its bit position.
01 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1010 1111 10000 10001 10010 10011 10100
Bit position
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
Encoded data bits p1 p2 d1 p4 d2 d3 d4 p8 d5 d6 d7 d8 d9 d10 d11 p16 d12 d13 d14 d15
p1 X X X X X X X X X X
...
p2 X X X X X X X X X X
Parity
bit p4 X X X X X X X X X
coverage
p8 X X X X X X X X
p16 X X X X X
Algorithm (decoding)
Department of Computer Science and Engineering
Network Lab CS602
1. To check for errors, check all of the parity bits. If all parity bits are correct, there is no error.
2. Otherwise, the sum of the positions of the erroneous parity bits identifies the erroneous bit.
3. If only one parity bit indicates an error, the parity bit itself is in error. Erroneous parity bit
means no. of one 1’s is odd. Correct parity bit means no. of one 1’s is even.
4. Extract the data bits if there is no error.
/**************************************************************************
* File Name : HamCode.c
*
* Description : Hamming Code generation for error detection and correction.
***************************************************************************/
#include<stdio.h>
#define MAX_SZ 50
int data[MAX_SZ],temp[MAX_SZ];
// finds 2^n
int power(int n)
{
int i,p=1;
for(i=1;i<=n;i++)
{
p=p*2;
}
return(p);
}
int hamming_code(int k)
{
int i,j,d=0;
int r = 1; //r = no.of parity bits
j = k;
for(i=1;i<=(k+r);i++)
{
if(i==power(d))
{
temp[i]=0;
d++;
}
else
temp[i]=data[j--];
}
return(r);
}
int main()
{
Department of Computer Science and Engineering
Network Lab CS602
int k,r;
int err_pos,i;
printf("no of databits\n");
scanf("%d",&k);
printf("enter the data to be transmitted(0's & 1's)\n");
for(i=1;i<=k;i++)
scanf("%d",&data[i]);
err_pos = find_parity_bits(k,r);
if (err_pos != 0)
{
if(check_err(err_pos,r))
printf("\n\nParity bit P%d is corrupted, data is fine", err_pos);
else
{
printf("\n\nData bit D%d is corrupted. ", err_pos);
// flip the error bit
temp[err_pos] = !(temp[err_pos]);
printf("\n\nCorrected data bits with new parity bits\n");
for(i=1;i<=(k+r);i++)
printf("%4d",temp[i]);
}
}
else
printf("No error");
return 0;
}
Experiment No. 7
Problem Statement:
Department of Computer Science and Engineering
Network Lab CS602
Write a program for simple RSA algorithm to encrypt and decrypt the data.
Theory:
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.
Modular arithmetic involving large numbers can be simplified by using the following property.
/**************************************************************************
Department of Computer Science and Engineering
Network Lab CS602
* File Name : RSA.c
*
* Description : Simple RSA algorithm to encrypt and decrypt the data.
***************************************************************************/
#include "stdafx.h"
#include<stdio.h>
#include<math.h>
#include<string.h>
return(e);
}
int main()
{
//long double
unsigned int plain_txt[MAX_SZ], cipher_txt[MAX_SZ];
unsigned int p,q,z,n,e,d;
char msg[MAX_SZ];
int i;
read:
do
{
printf("\n Enter two large prime numbers p and q:");
scanf("%d%d",&p,&q);
}while(p==q);
n=p*q;
z=(p-1)*(q-1);
printf("\n n=%d,z=%d",n,z);
if(n < 120)
{
printf("\n\nPlease keep n >= 122");
goto read;
}
e=find_encrypt_key(z);
d=find_decrypt_key(e,z);
for(i=0;i<strlen(msg);i++)
{
plain_txt[i]=msg[i];
printf("\n%c = %d:",plain_txt[i],plain_txt[i]);
}
return(0);
}
Experiment No. 8
Problem Statement:
Write a program for congestion control using Leaky bucket algorithm.
Theory:
Leaky bucket (proposed by Jonathan S. Turner, 1986) is a traffic shaping 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.
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.
Algorithm
1. The leaky bucket consists of a finite queue.
2. When a packet arrives, if there is room on the queue it is appended to the queue; otherwise, it is
discarded.
3. At every clock tick, one packet is transmitted
Department of Computer Science and Engineering
Network Lab CS602
/**************************************************************************
* File Name : LeakyBucket.c
*
* Description : A program to implement Leaky Bucket Algorithm
***************************************************************************/
#include "stdafx.h"
#include<stdio.h>
#include<stdlib.h>
#define BUCKETSIZE 250
#define OUTRATE 25
struct
{
int arrtime;
int weight;
}packet[15];
void read_packets(int n)
{
int i;
for(i=0;i<n;i++)
{
printf("Enter arrival time:");
scanf("%d",&packet[i].arrtime);
printf("Enter the packet size:");
scanf("%d",&packet[i].weight);
}
}
int n;
read_packets(n);
lky_bucket();
return 0;
}