Вы находитесь на странице: 1из 60

Computer Networks Lab Manual

PART - A
SIMULATION EXERCISES

Introduction
The network simulator can design and simulate a network with network protocols
used for research.
Network emulation
refers to actual network traffic passing through some software which might do
some analysis or modify the traffic.

Types of simulators
NIST
INSANE
REAL
NS
OPNET
NUTUns ( National chiao Tung Univercity network simulator) : is open
source , high quality and support many types of networks.

PART A

Department Of Information Science and Engineering

Page 1

Computer Networks Lab Manual

The following experiments shall be conducted using either NS / NCTUns or any other
suitable simulator.
1. Simulate a three nodes point to point network with duplex links between them. Set
the queue size and vary the bandwidth and find the number of packets dropped.
2. 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 between n1n3. Apply relevant applications over TCP and UDP agents changing the parameter and
determine the number of packets sent by TCP / UDP.
3.

Simulate the transmission of ping messages over a network topology consisting of 6


nodes and find the number of packets dropped due to congestion.

4. Simulate an Ethernet LAN using n nodes (6-10), change error rate and data rate
and compare throughput.
5. Simulate an Ethernet LAN using n nodes and set multiple traffic nodes and plot
congestion window for different source / destination.
6. Simulate simple ESS and with transmitting nodes in wire-less LAN by simulation
and determine the performance with respect to transmission of packets.

Department Of Information Science and Engineering

Page 2

Computer Networks Lab Manual

PART A Programs
The following experiments shall be conducted using NS2 or NCTUns-6.0 or other
suitable simulator

Steps to execute Part-A:


1.After grub loading select NCTUns kernel
2.others
3.username : root
Password : fedora
STEP1-open terminal1
[root@lab3~bin]# dispatcher
minimize terminal
STEP2-open terminal2
[root@lab3~bin]# coordinator
minimize terminal
STEP3-open terminal3
[root@lab3~bin]# nctunsclient

Then :
1> add nodes and create the network
2> configure the network devices
3> start the network and analyze the network behavior.

Department Of Information Science and Engineering

Page 3

Computer Networks Lab Manual

1. Simulate a three-node point-to-point network with a duplex link between them.


Set the queue size and vary the bandwidth and find the number of packets dropped.
Procedure:
1. Draw the n/w topology as specified in the draw topology mode of the simulator
Draw toplogy modeSelect the hub icon and drag it on the working window
Select the host icon on the toolbar and drag it on the working window
Repeat for another host
Select the link icon from the toolbar & make a connection b/w host1 and hub, host2 and
hub. Here the hub acts as node 3 in the point to point n/w topology
1. Go to edit mode and save the topology as a .tpl file
2. Double click on host1,click on the node editor & select MAC layer and then select
half duplex for hubs & in log statistics , select no of drop packets, no of collisions, &
throuput of outgoing packets & press ok. Select FIFO , set the queue size to 50 &
press ok . click on command box & type the following command Shown after
diagram
3. Double click on the link b/w host1 and hub to set the b/w to some initial value ,say
10mbps
4. Save the changes made to the topology .now click on the R button to run the
simulation
5. Now go to menu -> simulation -> run . execution
6. Play
7. Go to g-settings , plot the graph -> fileopen ->.results
Topology:-

For UDP connection


Sender:stg u 1024 100 1.0.1.2
Receiver:rtg u w log1

Department Of Information Science and Engineering

Page 4

Computer Networks Lab Manual

For TCP Connection:


Sender
stcp -p 7000 -l 1024 1.0.1.2
Receiver:
rtcp -p 7000 -l 1024
Parameters:Drop Packets and Collision Packets

Department Of Information Science and Engineering

Page 5

Computer Networks Lab Manual

2. Simulate a four-node point-to-point network and connect the link as follows:


Apply a TCP agent between n0 to n3 and apply a UDP agent between n1 and n3.
Apply relevant applications over TCP and UDP agents changing the parameters and
determine the number of packets sent by two agents.
Procedure:
1. Create the toplogy of three nodes connect these nodes to a hub
2. Goto edit mode & save the topology
3. Setup the tcp connection b/w n0-n3 and udp connection b/w n1-n3 as fallows
using the commands
4. Set the i/p throuput for the receiver & the o/p throuput for the sender in the log
file statistics
5. Back to edit mode
6. Run the simulation
7. Play
8. For results of graph, -> g-settings
->.plot graph
->select parameters
9. make a comparisons
Topology:-

For UDP connection


Sender:stg u 1024 100 1.0.1.2

Department Of Information Science and Engineering

Page 6

Computer Networks Lab Manual

Receiver:rtg u w log1
For TCP Connection:
Sender
stcp -p 7000 -l 1024 1.0.1.2
Receiver:
rtcp -p 7000 -l 1024
Parameters:Throughput of incoming and outgoing Packets

Department Of Information Science and Engineering

Page 7

Computer Networks Lab Manual

3 Simulate the transmission of ping messages over a network topology consisting of


6 nodes and find the number of packets dropped due to congestion.
Procedure:
1.click on the hub icon on the toolbar and drag it on the working window
2. select the 6 nodes and a suitable radius b/w the host and the hub
3. a single host is made to act as a receiver and other as sender
4.run the simulation
5.in the run mode from sending node the receiving node is pinged using ping
1.0.1.6
Note:the no of dropped packets are obtained only when the traffic is more is the
n/w
Command console:go to tools
Simulation time and change
Simulation time to 100
During run mode, doulble click host2 and then click command console and
execute
Ping 1.0.1.6
Topology:

Sender:stcp p 2000 l 1024 1.0.1.4


Receiver:rtcp p 2000 l 1024
Command Console:Goto tools-> simulation time and change Simulation time to 100. During run
mode, double click host 2 and then click command console. And execute the
following command.
ping 1.0.1.4
Parameters:Drop Packets and Collision Packets.

Department Of Information Science and Engineering

Page 8

Computer Networks Lab Manual

4. Simulate an Ethernet LAN using N nodes (6-10), change error rate and
data rate and compare throughput.
Procedure:
1. Connect one set of host with a hub and another set of host also through a hub
and connect these two hubs with a switch , this forms Ethernet LAN
2. To setup a tcp connection b/w a host or one hub & host or another hub using
following commands
TCP Connection:
Sender
(Stcp p portno l buffer size IP address)
stcp -p 7000 -l 1024 1.0.1.2
Receiver:
rtcp -p 7000 -l 1024
3. Setup the error rate , data rate in the physical layer, i/p and o/p throughput in
the MAC layer
4. Change error route and data route and compare throughput
5. View the results in file name results
Note:double click on reciver link and change BER to 0.00, run and check
Input Throughput and Output Throughput

Topology:-

TCP Connection:
Sender
stcp -p 7000 -i 1024 1.0.1.2
Receiver:
rtcp -p 7000 -l 1024
Double click on receiver link and change BER to 1.00, Run Again, and compare
Parameters:Throughput of outgoing Packets

Department Of Information Science and Engineering

Page 9

Computer Networks Lab Manual

5. Simulate an Ethernet LAN using N nodes and set multiple traffic nodes
and plot congestion window for different source/destination.
Procedure:
1. Connect one set of host with a hub and another set of hosts also through a hub and
connect these two hubs through a switch this forms an Ethernet LAN
2. Setup multiple traffic connection b/w the hosts on one hub and host on another
hub using the following
Stcp p 2000 l 1024 1.0.1.4
Rtcp p 2000 l 1024
3. Setup the collision log at the destination host in the MAC layer
4. Plot the congestion window , go to menu->tools->plotgraph->file->open filename
results-> filename .coll.log
5. Give the results in filename .results

Topology:-

Sender:stcp p 2000 l 1024 1.0.1.4


Receiver:rtcp p 2000 l 1024
Parameters:Receiver side Collision Packets and Drop Packets

Department Of Information Science and Engineering

Page 10

Computer Networks Lab Manual

6. Simulate simple BSS and with transmitting nodes in wireless LAN by


simulation and determine the performance with respect to transmission of packets.
Procedure:
1. Draw the topology consisting of a : route b:host c:WLAN d:WLAN access
point (two)
2. Go to tools menu, select the option wireless LAN -> mobile nodes
3. Generate infrastructure mobile nodes IP
4. A dialog box appear, entries to be done are
Subnet ID 8 gateway IP
Subnetid=2 & gateway Ip= 1.0.1.0
5. Here mobile nodes are the senders & the host is the receiver
6. For each mobile node, add a command
ttcp t -u s p 7000
ttcp t u s p 7001 for another node
7. For the receiver, add the following command
Ttcp r u s p 7000
8. Run the simulation
9. To see the results of the graph , go to g-settings ->plot graph ->file open>results, select the parameters required

Topology:-

Click on access point. Goto wireless interface and tick on show transmission range
and then click OK.
Double click on Router -> Node Editor and then
Left stack -> throughput of Incoming packets
Right stack -> throughput of Outgoing packets
Select mobile hosts and access points then click on.
Tools -> WLAN mobile nodes-> WLAN Generate infrastructure.
Subnet ID:
Port number of router (2)

Department Of Information Science and Engineering

Page 11

Computer Networks Lab Manual

Gateway ID: IP address of router


Mobile Host 1
ttcp t u s p 3000 1.0.1.1
Mobile Host 1
ttcp t u s p 3001 1.0.1.1
Host(Receiver)
ttcp r u s p 3000
ttcp r u s p 3001
Run and then play to plot the graph.

Department Of Information Science and Engineering

Page 12

Computer Networks Lab Manual

PART-B
Error detecting code using CRC-CCITT
Overview:
The accurate implementations (long-hand and programmed) of the 16-bit
CRC-CCITT specification, is as follows:
Width = 16 bits
Truncated polynomial = 0x1021
Initial value = 0xFFFF
Input data is NOT reflected
Output CRC is NOT reflected
No XOR is performed on the output CRC
Theoretical Concepts:
Important features of a standard CRC are that it:
Can be used to validate data
Is reproducible by others
The first feature above is easy to realize in a closed system if corruption
of data is infrequent (but substantial when it occurs). The term "closed
system" refers to a situation where the CRC need not be communicated
to others. A correct implementation of a 16-bit CRC will detect a
change in a single bit in a message of over 8000 bytes. An erroneous
CRC implementation may not be able to detect such subtle errors. If
errors are usually both rare and large (affecting several bits), then a
faulty 16-bit CRC implementation may still be adequate in a closed
system. The second feature above -- that the CRC is reproducible by
others -- is crucial in an open system; that is, when the CRC must be
communicated to others. If the integrity of data passed between two
applications is to be verified using a CRC defined by a particular
standard, then the implementation of that standard must produce the
same result in both applications -- otherwise, valid data will be reported
as corrupt.
Reproducibility may be satisfied by even a botched implementation of a
standard CRC in most cases -- if everyone uses the same erroneous
implementation of the standard. But this approach:
Modifies

the standard in ways that are both unofficial and


undocumented.
Department Of Information Science and Engineering

Page 13

Computer Networks Lab Manual


Creates

confusion when communicating with others who have not


adopted the botched implementation as the implied standard.
The CRC value for the 9-byte reference string, "123456789" is 0xE5CC.
The need to focus on the 16-bit CRC-CCITT (polynomial 0x1021) and not
CRC16 (polynomial 0x8005),are as follows :
Is

a straightforward 16-bit CRC implementation in that it doesn't


involve:
reflection of data
reflection of the final CRC value
Starts with a non-zero initial value -- leading zero bits can't affect the
CRC16 used by LHA, ARC, etc., because its initial value is zero.
It requires no additional XOR operation after everything else is done.
The CRC32 implementation used by Ethernet, Pkzip, etc., requires this
operation; less common 16-bit CRCs may require it as well.
The need to use a 16-bit CRC instead of a 32-bit CRC is as follows :
Can

be calculated faster than a 32-bit CRC.


Requires less space than a 32-bit CRC for storage, display or printing.
Is usually long enough if the data being safeguarded is fewer than
several thousand bytes in length, e.g., individual records in a database.
Example:
Calculationofthe16bitCRCCCITTforaonebyte
messageconsistingoftheletter"A":
Quotient=111100001110111101011001
poly=

10001000000100001)
1111111111111111010000010000000000000000
10001000000100001

redbitsareinitialvalue
11101111110111111
boldbitsaremessage
10001000000100001
bluebitsareaugmentation

Department Of Information Science and Engineering

Page 14

Computer Networks Lab Manual

11001111100111100
10001000000100001

10001111000111010
10001000000100001

00001110000110110
00000000000000000

00011100001101100
00000000000000000

00111000011011000
00000000000000000

01110000110110001
00000000000000000

11100001101100010
10001000000100001

11010011010000110
10001000000100001

10110110101001110

Department Of Information Science and Engineering

Page 15

Computer Networks Lab Manual

Program 1:
Write a program for error detecting code using CRC-CCITT (16-bits).
#include<stdio.h>
#include<string.h>
#define N strlen(g)

char t[128], cs[128], g[]="10001000000100001";


int a,e,c;

void xor(){
for(c=1;c<N;c++)
cs[c] = ((cs[c] == g[c])?'0':'1');
}

void crc(){
for(e=0;e<N;e++) cs[e]=t[e];
do {

Department Of Information Science and Engineering

Page 16

Computer Networks Lab Manual

if(cs[0]=='1') xor();
for(c=0;c<N-1;c++) cs[c]=cs[c+1];
cs[c]=t[e++];
}while(e<=a+N-1);
}

void main()
{
//

clrscr();
printf("\n Enter the data in binary : ");
scanf("%s",t);
printf("Generating poynomial is : %s", g);
a = strlen(t);
for(e=a;e<a+N-1;e++) t[e]='0';
printf("\n Modified t[u] is : %s",t);
crc();
printf("\nChecksum is : %s", cs);
for(e=a;e<a+N-1;e++) t[e]=cs[e-a];
printf("\nFinal CodeWord is : %s\n",t);

Department Of Information Science and Engineering

Page 17

Computer Networks Lab Manual

printf("\nTest Error detection 0(yes) 1(no) ?:");


scanf("%d",&e);

if(e==0){
printf("\nEnter position where error is to inserted :");
scanf("%d",&e);
t[e]=(t[e]=='0')?'1':'0';
printf("\nErrorneous data : %s\n",t);
}
crc();
for(e=0;(e<N-1)&&(cs[e]!='1');e++);
if(e<N-1) printf("\nError detected\n");
else printf("\nNo error Detected\n");
//

getch();

Output:

Department Of Information Science and Engineering

Page 18

Computer Networks Lab Manual

DISTANCE VECTOR ALGORITHM


Background: One of the most popular & dynamic routing algorithms, the
distance vector routing algorithms operate by using the concept of each
router having to maintain a table( ie., a vector ), that lets the router know the
best or shortest
distance to each(y),c(x,z)+D
destination (y)}
and the next hop to get to there.
D (y)=min{c(x,y)+D
x
y
z
Also know as Bellman
Ford(1957) and Ford Fulkerson (1962). It was the
=min{2+0,7+1}=2
original ARPANET algorithm.
Algorithm
router
a table containing entries for
cost Overview:Each
to
cost
to maintains cost
to
and indexed
in the subnet. Table
contains two parts :
x y by
z each otherx router
y z
x
y
z
1.A preferred outing line.
x 0 2 of7time or distance
x 0 2 to
3 that destination.
2.Estimate
x 0 2 3
y
The metric
used
here isythe
transmission
delay
destination. This
2 0 1
y 2 to0each
1
z maybe
metric
hops,
length,
etc.
z 7
number of
1 queue
0
z 3
from
1 0
from
The router is assumed to know the distance
from
metric to each of its
cost to
cost tothe delay is calculated
cost to by sending echo
neighbours.Across
the network
y
z of neighbours.
x y z
packetsxtoyeach
x y z
2
1
Example:
x

x 0 2 7
x 0 2 3
y 2 0 1
z 3 1 0
from
cost to
x y z

y 2 0 1
z
from
cost to
x y z

y 2 0 1
z 7 1 0
from
cost to
x y z

y

z 71 0
from

x 0 2 7
x 0 2 3
Department
y 2 0Of 1Information Science
y 2 and
0 Engineering
1
z 3 1 0
z 3 1 0
from
from

Page 19

Computer Networks Lab Manual

Program 3:
Write a program for distance vector algorithm to find suitable path for
transmission.
#include<stdio.h>
#include<string.h>

struct node
{
int dist[20]; // cost
int from[20]; // nexthop
}rt[10];

Department Of Information Science and Engineering

Page 20

Computer Networks Lab Manual

int main()
{
int dmat[20][20],i,j,k;
int n=i=j=k=0,count=0;
printf("Enter The Number of Nodes in the Network\n");
scanf("%d",&n);
printf("Enter The Cost Matrix( 999 if there is no direct link)\n");
for(i=0 ;i<n;i++)
for(j=0;j<n;j++)
{
scanf("%d",&dmat[i][j]);
dmat[i][i]=0;

// node A to node A cost is zero

rt[i].dist[j]=dmat[i][j]; // distance from i to j


rt[i].from[j]=j;
}
do
{
count=0;
for(i=0 ;i<n;i++)

Department Of Information Science and Engineering

Page 21

Computer Networks Lab Manual

for(j=0;j<n;j++)
for(k=0;k<n; k++)
if(rt[i].dist[j] > dmat[i][k]+rt[k].dist[j]) // finding new route
with less cost
{
rt[i].dist[j] = rt[i].dist[k] + rt[k].dist[j];// new route with
less cost
rt[i].from[j]=k;

// via node k

count++;
}
}while (count!=0);

for(i=0;i<n;i++)
{
printf("\n\nRouting Table Of Router %c Is\n",65+i);
printf("

Destination

NextHop

Distance \n");

for(j=0;j<n;j++)
printf("\t%c\t\t%c\t\t%d\n",65+j, 65+rt[i].from[j], rt[i].dist[j]);
}
}

Department Of Information Science and Engineering

Page 22

Computer Networks Lab Manual

Output:

CLIENT SERVER PROGRAM USING SOCKET


PROGRAMMING
OVERVIEW: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{

Department Of Information Science and Engineering

Page 23

Computer Networks Lab Manual

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
};
BACKGROUND REQUIRED:
1.UNIX File I/O system calls
2.UNIX IPC system calls
3.UNIX socket programming
THEORETICAL CONCEPTS:
Most interprocess communication uses the client server model. These terms
refer to the two processes which will be communication with each other.
One of the two processes , the client , connects to the other process, the
server, typiceally to make a request for information. A good analogy is a
person who makes a phone call to another person.
Notice that the client needs to know of the existence of and the address of
the server, but the server does not need to know the adresss of(or even the
existence of) the client prior to the connection being established. Notice also
that once a connection is established, both sides can send and receive
information.
The system calls for establishing a connection are somewhat different for the
client and the server, but both involve the basic construct of a socket. A
socket is one end of an interprocess communication channel. The two
processes each establish their own socket.

Department Of Information Science and Engineering

Page 24

Computer Networks Lab Manual

The steps involved in establishing a socket on the client side are as follows1.Create a socket with the socket() system call .
2.Connect the socket to the address of the server using the connect()
system call.
3.Send and receive data.There are a number of ways to do this, but the
simplest is to use the read() and write() systen calls.
The stepd involved in establishing a socket on the server side are as
follows1.Create a socket with the socket() system call.
2.Bind the socket to an address using the bind() system call. For a
server socket on the internet,an address consists of a port number on the
host machine.
3.Listen for connections with the listen() system call.
4.Acept a connection with the accept() system call. This call typically
blocks until a client connects with the server.
5.Send and receive the data.
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.

Department Of Information Science and Engineering

Page 25

Computer Networks Lab Manual

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:1.<sys/types.h> -prerequisite typedefs.
2.<errno.h> -names for erno values (error numbers)
3.<sys/socket.> - struct sock addr ;system prototypes and constants .
4.<netdb.h.h> - network info lookup prototypes and structures.
5.<netinet/in.h> - struct sockaddr_in; byte ordering macros.
6.<arpa/inet.h> - utility function prototypes.

Program 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.
Client program:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>

Department Of Information Science and Engineering

Page 26

Computer Networks Lab Manual


#include<sys/socket.h>

//for sockaddr

#include<netinet/in.h>

//for sockaddr_in

#include<sys/fcntl.h>

//for O_RDONLY

#include<netdb.h>
#define SERVER_PORT 2234
#define BUF_SIZE 4096

int main()
{

int c,s,bytes;
char buf[BUF_SIZE],fname[255];
struct hostent *h;
struct sockaddr_in channel;

printf("Enter the file name:");


gets(fname);

h=gethostbyname("localhost");

//get server address

if(!h){
printf("gethostbyname failed");
exit(0);
}

memset(&channel,0,sizeof(channel));
'channel'
channel.sin_family=AF_INET;

//allocate memory for


//assign values

memcpy(&channel.sin_addr.s_addr,h->h_addr,h->h_length);
channel.sin_port=htons(SERVER_PORT);

s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);

Department Of Information Science and Engineering

Page 27

Computer Networks Lab Manual

if(s<0) printf("socket creation failed"), exit(0);

c=connect(s,(struct sockaddr*) &channel, sizeof(channel));


if(c<0) printf("connect failed"),

write(s, fname, strlen(fname));


channel

exit(0);

//write the file name to

while(1)
{
channel

bytes=read(s,buf,BUF_SIZE);
if (bytes<=0) exit(0);

//read file contents form the


//sent by server

write(1,buf,bytes);
}
}

Server program:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<sys/socket.h>

//for sockaddr

#include<netinet/in.h>

//for sockaddr_in

#include<sys/fcntl.h>

//for O_RDONLY

#include<netdb.h>
#define SERVER_PORT 2234
#define BUF_SIZE 4096
Department Of Information Science and Engineering

Page 28

Computer Networks Lab Manual

int main()
{

int s,b,l,fd,sa,bytes,on=1;
char buf[BUF_SIZE],fname[255];
struct sockaddr_in channel;

s=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP);
if(s<0) printf("socket failed"), exit(0);
//
setsockopt(s,SOL_SOCKET,SO_REUSEADDR,
(char*)&on,sizeof(on)); // optional

memset(&channel,0,sizeof(channel)); //allocate memory for 'channel'


channel.sin_family=AF_INET;

//assign values

channel.sin_addr.s_addr=htonl(INADDR_ANY);
channel.sin_port=htons(SERVER_PORT);

b=bind(s,(struct sockaddr*)&channel,sizeof(channel));
if(b<0) printf("bind failed"),

listen(s,5);

exit(0);

//listen channel for any request

Department Of Information Science and Engineering

Page 29

Computer Networks Lab Manual

while(1)
{

printf("\n\nWaiting for request:\n");


sa=accept(s,0,0);

//create a socket for communication

if(sa<0) printf("accept failed");

memset(fname,0,sizeof(fname));
read(sa,fname,BUF_SIZE);

//read file name from

channel
printf("requested filename: %s",fname);
fd=open(fname,O_RDONLY);

//open file to

READ
if(fd<0)
{

printf("\nError message sent to client\n");


write(sa,"could not open requested file",40);

}
else {
while(1)
{

bytes = read(fd,buf,BUF_SIZE);

//read file & store

in buf
if(bytes<=0) break;
write(sa,buf,bytes);

//write the contents to channel

Department Of Information Science and Engineering

Page 30

Computer Networks Lab Manual

}
close(fd);

//close connection

}
close(sa);
}
}
Output:

EXECUTION INSTRUCTIONS:
There are two programs(Server-side & Client-side) to be typed on an editor
(eg vi or kdevelop), exit the editor after saving the progarm, complile the
programs on different terminals using the command cc <programname>.c
-o <output filename> and then the command ./<output filename> is
entered if no errors are encountered(else correct the errors and then perform
the above).
1.Compile and execute the Server side program. Then in the other terminal
compile and execute the Client side program.

Department Of Information Science and Engineering

Page 31

Computer Networks Lab Manual

MESSAGE QUEUES / FIFOs AS IPC CHANNELS


Client Server communication using FIFO as IPC
OVERVIEW:
FIFO's is used to send data between a Client and Server. If we have a server
that is contacted by numerous clients, each client can write its request to a
well-known(i.e, the pathname is known by all clients) FIFO that the server
creates. The figure below shows this arrangement. Since there are multiple
writers for the FIFO, the requests sent by the clients to the server need to be
less than PIPE_BUF bytes in size. This prevents any interleaving of the
client writes.

Department Of Information Science and Engineering

Page 32

Computer Networks Lab Manual

The problem in using FIFO's for this type of client-server communication is


how to send replies back from the server to each client. A single FIFO can't
be used, as the clients would never know when to read their response, versus
responses for other clients. One solution is for each client to send its process
ID with the request. The server then creates a unique FIFO for each client,
using a pathname based on the client's process ID.
Server

Well-known
FIFO

Client-specific
FIFO

Client

Client-specific
FIFO

Client

BACKGROUND REQUIRED:
1.UNIX File I/O system calls
2.UNIX IPC system calls
ALGORITHM: There are two programs- Server side & Client side.
Server side:
1.Create a well-known FIFO using mknod command.
Ex: mknod(<fifo name>, S_IFIFO | 0666 , 0)
2.Open the above FIFO in readonly mode to accept requests from
the clients.
3.When the client opens the other end of FIFO in writeonly mode
then read the contents and store the request(pathname of file) in a
buffer.
4.Now create another FIFO(client-specific) in writeonly mode to
send the reply(contents of the file requested)
5.Open the file requested by client and write the contents into the

Department Of Information Science and Engineering

Page 33

Computer Networks Lab Manual

client-speicfic FIFO and terminate the connection.


Client side:
1.Open the well-known Server FIFO in write mode.
2.Write the pathname of file into this FIFO and send as a request.
3.Now open the Client-specific FIFO in read mode and wait for
reply from server.
4.When the contents of file are available on this FIFO display it on
the terminal.

Program 5
Implement the above program using as message queues of FIFOs as IPC
channel.
server program:
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#define FIFO1_NAME "fifo1"
#define FIFO2_NAME "fifo2"
int main()
{
char p[100],f[100],c[3000];

Department Of Information Science and Engineering

Page 34

Computer Networks Lab Manual

int num,num2,f1,fd,fd2,in;
mknod(FIFO1_NAME,S_IFIFO | 0666,0);
mknod(FIFO2_NAME,S_IFIFO | 0666,0);
printf("SERVER ONLINE\n");
fd = open(FIFO1_NAME,O_RDONLY);
printf("Client online \n waiting for request \n");
while(1){
if((num = read(fd, p, 100))==-1)
perror("Read Error\n");
else{
p[num] ='\0';
if((f1=open(p,O_RDONLY))<0){
printf("Server %s not found\n",p);return(0);exit(1);
}
else
{
printf("Server %s found \n transferring the contents\n",p);stdin =
fdopen(f1,"r");
if(fgets(c,3000,stdin)!=NULL){
fd2 = open(FIFO2_NAME,O_WRONLY);
if(num2 = write(fd2,c,strlen(c))== -1)
perror("Transfer error\n");
else
printf("Server:Transfer Completed size=%d\n",strlen(c) );
}
else
perror("read Error\n");
exit(1);
}
}
}
}
Client program:
#include<stdio.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>

Department Of Information Science and Engineering

Page 35

Computer Networks Lab Manual

#include<fcntl.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#define FIFO1_NAME "fifo1"
#define FIFO2_NAME "fifo2"
int main()
{
char p[1000],f[1000],c[3000];
int num,num2,f1,fd,fd2;
mknod(FIFO1_NAME,S_IFIFO | 0666,0);
mknod(FIFO2_NAME,S_IFIFO | 0666,0);
printf("Waiting for server\n");
fd=open(FIFO1_NAME,O_WRONLY);
printf("server online\n Client:Enter the Path\n");
while(gets(p)!=feof(stdin)){
if((num= write(fd,p,strlen(p)))==-1)
perror("write Error\n");
else
{
printf("waiting for reply\n");
fd2=open(FIFO2_NAME,O_RDONLY);
if((num2=read(fd2,c,300))==-1)
perror("Transfer error\n");
else{
printf("File Recevied \n displaying the contents \n");
if(fputs(c,stdout)==EOF)
perror("Print error\n");
exit(1);
}
}
}
}
Output:
clientterminal

Server terminal

Department Of Information Science and Engineering

Page 36

Computer Networks Lab Manual

cc client.c
./a.out
Waiting for server
Server online
Client:
enter the path:/ns/nwlab/ns2.33/file
Waiting for reply
File received
Displaying the contents:
Bangalore college of engineering

cc server.c
./a.out
Server online
Client online, waiting for the request
Waiting for request
Server /ns/nwlab/ns2.33/file found
Transferring the contents
Server:transfer completed size=33

EXECUTION INSTRUCTIONS:

There are two programs(Server-side & Client-side) to be typed on an editor,


exit the editor after saving the program, compile the programs on different
terminals using the command cc <program_name>.c and then the
command ./a.out is entered if no errors are encountered(else correct the
errors and then perform the above).
1.Compile and execute the Server side program first then in the other
terminal compile and execute the client side program.
2.Enter the pathname of any file on the system as a request to the Server and
wait for reply.
3.Now switch to Server terminal and check if the file requested is present or
not and the status of Server. If the file is found then switch to the Client
terminal and watch the contents of file displayed on the terminal. Else it
displays that file is not found with pathname.

Department Of Information Science and Engineering

Page 37

Computer Networks Lab Manual

RSA ALGORITHM
Overview:
The RSA Public key algorithm was invented in 1977 by Ron Rivest, Adi
Shamir and Leonard Adelman (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.
Theoretical Concepts:
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). RSA depends on
prime numbers in key generation. It also uses strong primes, numbers

Department Of Information Science and Engineering

Page 38

Computer Networks Lab Manual

whose factors of the prime are also primes.


The RSA algorithm:
Key generation:
1)Select random prime numbers p and q, and check that p != q
2)Compute modulus n = pq
3)Compute phi = (p - 1)(q - 1)
4)Select public exponent e, 1 < e < phi such that gcd(e,phi) = 1
5)Compute private exponent d = e^-1 mod phi
6)Public key is {n, e}, private key is d
Encryption: c = m*e mod n, decryption: m = c*d mod n
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.
(gcd = greatest common divisor, using the Euclidean algorithm)
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) ).
Example of RSA with small numbers:
p = 47, q = 71, compute n = p*q = 3337
Compute phi = 46 * 70 = 3220
Let e be 79, compute d = 79-1 mod 3220 = 1019

Department Of Information Science and Engineering

Page 39

Computer Networks Lab Manual

Public key is n and e, private key d, discard p and q.


Encrypt message m = 688, 68879 mod 3337 = 1570 = c.
Decrypt message c = 1570, 15701019 mod 3337 = 688 = m.

Program 6:
Write a program for simple RSA algorithm to encrypt and decrypt the
data.
#include<stdio.h>
#include<stdlib.h>
int gcd(int a,int b)
{
int c;
while(a!=b)
{
if(a<b)
{
c=a;a=b;b=c;
}
a-=b;
}
return a;
}
int mod(int m,int e,int n)
{
int a=1;
while(e)
{
a=(a*m)%n;
e--;
}
return a;

Department Of Information Science and Engineering

Page 40

Computer Networks Lab Manual

}
int main()
{
int p,q,n,e,m,c,d,x,z;
int en[100],de[100],j=0;
printf("\nenter the value of p & q\n");
scanf("%d%d",&p,&q);
n=p*q;
z=(p-1)*(q-1);
for(e=1;e<n;e++)
{
if(gcd(e,z)==1)
{
en[j]=e;
printf(" %d",en[j++]);
}
}
printf("\nchoose e\n");
scanf("%d",&e);
if(gcd(e,z)!=1)
{
printf("\nthe value not from list\n");
exit(0);
}
printf("enter the character to be encrypted:\n");
scanf("%d",&m);
printf("before encryption:%d\n",m);
c=mod(m,e,n);
printf("after encryption:%d\n",c);
for(d=0;d<n;d++)
{
if((d*e)%z==1)
{
de[j]=d;
printf(" %d",de[j++]);
}
}

Department Of Information Science and Engineering

Page 41

Computer Networks Lab Manual

printf("\nchoose D\n");
scanf("%d",&d);
x=mod(c,d,n);
printf("after decryption=%d\n",x);
return 0;
}

Output:
Enter the value of p& q: 3 5
1 3 5 7
Choose e: 7
Enter the character to be encrypted: 3
Before encryption : 3
After encryption: 12
7
Choose d: 7
After decryption : 3

HAMMING CODES
Overview:
Developed by 1947 Richard. W. Hamming for detecting and correcting
single bit errors in transmitted data. This technique requires that three parity
bits (or check bits) be transmitted with every four data bits. The algorithm is
Department Of Information Science and Engineering

Page 42

Computer Networks Lab Manual

called a (7, 4) code, because it requires seven bits to encoded four bits of
data.
Theoretical Concepts :
Background Concepts Required:
1.
matrix multiplication
2.
modulo 2 arithmetic
3.
parity.
Parity:A parity bit is an extra bit that forces a binary string to have a specific
parity.
Two types:
1.Even(Even number of 1's i.e., the modulo 2 sum of the bits is 0)
2.Odd (Odd number of 1's i.e., the modulo 2 sum of the bits is 1)
The table below lists all possible three bit values and value of a parity bit
required to create a four bit sequence with even parity.
3 Bit String Parity Bit
Verification
000
001
010
011
100
101
110
111

0
1
1
0
1
0
0
1

0+0+0+0
0+0+1+1
0+1+0+1
0+1+1+0
1+0+0+1
1+0+1+0
1+0+1+0
1+1+1+1

=
=
=
=
=
=
=
=

0
0
0
0
0
0
0
0

Table 1. Even Parity


It is very common for communication protocols to specify that a block of
bits will be transmitted with a specific parity. If a block of data arrives at its
intended destination with a parity other than the specified parity, it must be
the case that at least one of the bits has been corrupted. A single parity bit is
not sufficient to identify an even number of bits with errors, nor is it
sufficient to allow the receiver to correct an error. Hamming codes use
multiple parity bits to allow for error correction.

Department Of Information Science and Engineering

Page 43

Computer Networks Lab Manual

Encoding
Traditional Hamming codes are (7, 4) codes, encoding four bits of data into
seven bit blocks (a Hamming code word). The extra three bits are parity bits.
Each of the three parity bits are parity for three of the four data bits, and no
two parity bits are for the same three data bits. All of the parity bits are even
parity.
Example:
Given: data bits d1, d2, d3, and d4
A (7, 4) Hamming code may define parity bits p1, p2, and p3 as
p1 = d2 + d3 + d4
p2 = d1 + d3 + d4
p3 = d1 + d2 + d4
There's a fourth equation for a parity bit that may be used in Hamming
codes:
p4 = d1 + d2 + d3
Valid Hamming codes may use any three of the above four parity bit
definitions.
Valid Hamming codes may also place the parity bits in any location within
the block of 7 data and parity bits. Two Hamming codes with different parity
bits or parity bits in a different bit position are considered equivalent. They
will produce different results, but they are still Hamming codes.
One method for transforming four bits of data into a seven bit Hamming
code word is to use a 47 generator matrix [G].
Define d to be the 14 vector [d1 d2 d3 d4]
It's possible to create a 47 generator matrix [G] such that the product
modulo 2 of d and [G] (d[G]) is the desired 17 Hamming code word. Here's
how it's done:
Step 1: Represent each data bit with a column vector as follows:
|1|
d1 = | 0 |
|0|
|0|

Department Of Information Science and Engineering

Page 44

Computer Networks Lab Manual

|0|
d2 = | 1 |
|0|
|0|
|0|
d3 = | 0 |
|1|
|0|
|0|
d4 = | 0 |
|0|
|1|
Step 2:Represent each parity bit with a column vector containing a 1 in the
row corresponding to each data bit included in the computation and a zero in
all other rows. Using the parity bit definitions from the example above:
|0|
p1 = | 1 |
|1|
|1|
|1|
p2 = | 0 |
|1|
|1|
|1|
p3 = | 1 |
|0|
|1|

Department Of Information Science and Engineering

Page 45

Computer Networks Lab Manual

Step 3:Arrange the column vectors from the previous steps into a 47 matrix
such that the columns are ordered to match their corresponding bits in a code
word.
Using the vectors from the previous steps, the following will produce code
words of the form [p1 p2 p3 d1 d2 d3 d4]
|0111000|
G= |1010100|
|1100010|
|1110001|
Arranging the columns in any other order will just change the positions of
bits in the code word.
Example:
Encode the data value 1010 using the Hamming code defined by the matrix
G (above).
| (1 0) + (0 1) + (1 1) + (0 1) |
|1|
| (1 1) + (0 0) + (1 1) + (0 1) |
|0|
|0111000 |
|1|
|1010 |
|1010100 |
=|1|
|1100010 |
|0|
|1110001 |
|1|

| (1 1) + (0 1) + (1 0) + (0 1) |
=

| (1 1) + (0 0) + (1 0) + (0 0) |
| (1 0) + (0 1) + (1 0) + (0 0) |
| (1 0) + (0 0) + (1 1) + (0 0) |
| (1 0) + (0 0) + (1 0) + (0 1) |

|0|
So 1010 encodes to 1011010. Equivalent Hamming codes represented by
different generator matrices will produce different results.

Department Of Information Science and Engineering

Page 46

Computer Networks Lab Manual

Decoding
In a world without errors decoding a Hamming code word would be very
easy. Just throw out the parity bits. The encoding example produced a 7 bit
code word. Its parity bits are 101 and its data bits are 1010. If you receive a
1011010, just decode it as 1010. But what happens if you receive a code
word with an error and one or more of the parity bits are wrong.
Suppose the Hamming code defined by the matrix G in the example above is
being used and the code word 1011011 is received. How is that word
decoded? The first step is to check the parity bits to determine if there is an
error.
Arithmetically, parity may be checked as follows:
p1 = d2 + d3 + d4 = 0 + 1 + 1 = 0
p2 = d1 + d3 + d4 = 1 + 1 + 1 = 1
p3 = d1 + d2 + d4 = 1 + 0 + 1 = 0
In this case every parity bit is wrong. p1, p2, and p3 should have been 010,
but we received 101.
Parity may also be validated using matrix operations. A 37 parity check
matrix [H] may be constructed such that row 1 contains 1s in the position of
the first parity bit and all of the data bits that are included in its parity
calculation. Row 2 contains 1s in the position of the second parity bit and all
of the data bits that are included in its parity calculation. Row 3 contains 1s
in the position of the third parity bit and all of the data bits that are included
in its parity calculation.
Example:
Using the code from example above, the matrix H may be defined as
follows:
H=

|1000111|
|0101011|
|0011101|

Multiplying the 37 matrix [H] by a 71 matrix representing the encoded


data produces a 31 matrix called the "syndrome". There are two useful
proprieties of the syndrome. If the syndrome is all zeros, the encoded data is

Department Of Information Science and Engineering

Page 47

Computer Networks Lab Manual

error free. If the syndrome has a non-zero value, flipping the encoded bit that
is in the position of the column matching the syndrome will result in a valid
code word.
Example:
Using the parity check matrix from the example above we can correct and
verify the code word 1011011.
|1|
|0|
| 1000111 | | 1 | |(11)+(00)+(01)+(01)+(10)+(11) +(11) |
|
1|
| 0101011 | | 1 | = |(00)+(10)+(01)+(11)+(00)+(11)+(11) | = |
1|
| 0011101 | | 0 | |(01)+(00)+(11)+(11)+(10)+(01)+(11) |
|
1|
|1|
|1|
A column of all 1s is not the column of all 0s, so there is a parity error.
Looking back at the matrix [H], you will see that the seventh column is all
1s, so the seventh bit is the bit that has an error. Changing the seventh bit
produces the code word 1011010.

|1000111|
|0|
|0101011|
= |0|
|0011101|
|0|

|1|
|0|
|1|

|(11)+(00)+(01)+(01)+(10)+(11)+(10) |

| 1 | = |(00)+(10)+(01)+(11)+(00)+(11)+(10) |
|0|

|(01)+(00)+(11)+(11)+(10)+(01)+(10) |

|1|
|0|
Sure enough 1011010 is a valid code word. As I stated at the top of this
section remove the parity bits to get the encoded value. In this case 1011011

Department Of Information Science and Engineering

Page 48

Computer Networks Lab Manual

was likely transmitted as 1011010, which encodes 1010.

Program 7:
Write a program for Hamming Code generation for error detection and
correction.
#include<stdio.h>
#include<unistd.h>
#include<math.h>
int main()
{
int i,j;
char data[4];
int d1[5],d2[5],d3[5],d4[5];
int p1[5],p2[5],p3[5];
int gmatrix[4][8];
int encode[7]={0,0,0,0,0,0,0};
int edata[7]={0,0,0,0,0,0,0};
int errdig;
int syn[3]= {0,0,0};
int hmatrix[3][7] = { 1,0,0,0,1,1,1,
0,1,0,1,0,1,1,
0,0,1,1,1,0,1
};
int choice;
system("clear");
for(;;)
{
printf("\n 1.ENCODE ");

Department Of Information Science and Engineering

Page 49

Computer Networks Lab Manual

printf("\n 2.DECODE ");


printf("\n 3.EXIT ");
printf("\n Enter your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("\n Enter 4 data bits\n");
scanf("%s",data);
for(i=0;i<4;i++)
{
d1[i]=d2[i]=d3[i]=d4[i]=0;
p1[i]=p2[i]=p3[i]=1;
}
d1[0]=d2[1]=d3[2]=d4[3]=1;
p1[0]=p2[1]=p3[2]=0;
for(i=0;i<4;i++)
gmatrix[i][0]=p1[i];
for(i=0;i<4;i++)
gmatrix[i][1]=p2[i];
for(i=0;i<4;i++)
gmatrix[i][2]=p3[i];
for(i=0;i<4;i++)
gmatrix[i][3]=d1[i];
for(i=0;i<4;i++)
gmatrix[i][4]=d2[i];
for(i=0;i<4;i++)
gmatrix[i][5]=d3[i];
for(i=0;i<4;i++)
gmatrix[i][6]=d4[i];
printf("\n The generator matrix is\n\n");
for(i=0;i<4;i++)
{
for(j=0;j<7;j++)
{
printf("%d\t",gmatrix[i][j]);
}
printf("\n");
}

Department Of Information Science and Engineering

Page 50

Computer Networks Lab Manual

for(i=0;i<7;i++)
for(j=0;j<4;j++)
encode[i]=encode[i] + ( data[j] * gmatrix[j][i]);
printf("\n the encoded data is \n");
for(i=0;i<7;i++)
{
encode[i]=encode[i] % 2;
}
for(i=0;i<7;i++)
printf("%d",encode[i]);
break;
case 2:
printf("\n enter the encoded data \n");
for(i=0;i<7;i++)
scanf("%d",&edata[i]);
for(i=0;i<3;i++)
for(j=0;j<7;j++)
syn[i]=syn[i] + ( hmatrix[i][j] * edata[j] );
for(i=0;i<3;i++)
syn[i]=syn[i] % 2;
errdig = 4 * syn[0] + 2 * syn[1] + 1 * syn[2];
if (errdig == 0)
printf("\n Error free data \n");
else
{
printf("\n error in the bit number %d\n",errdig);
errdig--;
if(edata[errdig] == 1)
edata[errdig]=0;
else
edata[errdig]=1;
}
printf("\n the actaual data error free data : ");
for(i=3;i<7;i++)
printf("%d",edata[i]);
break;
default : exit(0);
}
}

Department Of Information Science and Engineering

Page 51

Computer Networks Lab Manual

}
Output:
cc prgm8.c
./a.out
1.Encode
2.Decode
3.Exit
Enter your choice : 1
Enter the 4 bits : 1101
The generator matrix is
0
1
1
1
1
0
1
0
1
1
0
0
1
1
1
0

0
1
0
0

0
0
1
0

0
0
0
1

The encoded data is:


0011101
1.Encode
2.Decode
3.Exit
Enter your choice : 2
Enter the encoded data :
0
0
1
1
1
0
1
Error free data
The actual data error free data: 1101
1.Encode
2.Decode
3.Exit
Enter your choice : 3
LEAKY BUCKET ALGORITHM
The leaky-bucket implementation is used to control the rate at which traffic
is sent to the network. A leaky bucket provides a mechanism by which
bursty traffic can be shaped to present a steady stream of traffic to the
network, as opposed to traffic with erratic bursts of low-volume and highvolume flows.

Department Of Information Science and Engineering

Page 52

Computer Networks Lab Manual

Traffic analogy An appropriate analogy for the leaky bucket is a scenario in


which four lanes of automobile traffic converge into a single lane. A
regulated admission interval into the single lane of traffic flow helps the
traffic move. The benefit of this approach is that traffic flow into the major
arteries (the network) is predictable and controlled. The major liability is
that when the volume of traffic is vastly greater than the bucket size, in
conjunction with the drainage-time interval, traffic backs up in the bucket
beyond bucket capacity and is discarded.

The Leaky-bucket algorithm

The algorithm can be conceptually understood as follows:


Arriving

packets (network layer PDUs) are placed in a bucket with a


hole in the bottom.
The bucket can queue at most b bytes. If a packet arrives when the
Department Of Information Science and Engineering

Page 53

Computer Networks Lab Manual

bucket is full, the packet is discarded.


Packets drain through the hole in the bucket, into the network, at a
constant rate of r bytes per second, thus smoothing traffic bursts.
The size b of the bucket is limited by the available memory of the system.
Sometimes the leaky bucket and token algorithms are lumped together under
the same name.

Program 8:
Write a program for Congestion control using the leaky bucket
algorithm.
#include<stdio.h>
#define min(x,y) ((x) < (y) ? (x) : (y))

Department Of Information Science and Engineering

Page 54

Computer Networks Lab Manual

#define MAX 25
int main()
{
int cap, oprt, nsec, cont, i=0,dr=0, inp[MAX]={0}, ch, x;
printf("\n\nLEAKY BUCKET ALGORITHM\n");
printf("\nEnter bucket size : ");
scanf("%d",&cap);
printf("\nEnter output rate (no..of pkts/sec) : ");
scanf("%d",&oprt);
do{
",i+1);

printf("\nEnter the no..of packets entering at second %d :

scanf("%d",&inp[i++]);
printf("Enter 1 to insert packets or 0 to quit : ");
scanf("%d",&ch);
} while(ch);
nsec=i;
printf("\nSecond : Packets sent : Packets recvd : In bucket:
Dropped\n");
for(cont=i=0; cont || (i<nsec); i++)
{
printf(" (%d) :",i+1);
printf(" (%d)\t: ",/*nsec?*/inp[i]/*:0*/);
printf(" (%d)\t: ",min(cont+inp[i],oprt));
if((x=cont+inp[i]-oprt)>0)
if(x>cap)
{
cont=cap;
dr=x-cap;
}

else
{
cont=x;

Department Of Information Science and Engineering

Page 55

Computer Networks Lab Manual

dr=0;
}
else
cont=0;
printf(" %d\t:",cont);
printf(" %d\n",dr);
}
return 0;
}
Output :
Leaky bucket algorithm:
Enter bucket size: 3
Enter the output rate(No. of packets/sec): 2
Enter the no. of packets sent at second 1: 6
Enter 1 to insert packets or 0 to quit:0
Second : packet sent :
packet recvd :
(1)
(6)
(2)
(2)
(0)
(2)
(3)
(0)
(1)

In bucket :
(3)
(1)
(0)

Dropped
(1)
(0)
(0)

Viva Questions

Department Of Information Science and Engineering

Page 56

Computer Networks Lab Manual

1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.

What are functions of different layers in OSI And TCP/IP model?


Differentiate between TCP/IP Layers and OSI Layers
Why header is required?
What is the use of adding header and trailer to frames?
What is encapsulation?
Why fragmentation requires?
What is MTU?
Which layer imposes MTU?
Differentiate between flow control and congestion control.
Differentiate between Point-to-Point Connection and End-to-End connections.
Which are protocols running in different layers?
What is Protocol Stack?
Differentiate between TCP and UDP.
Differentiate between Connectionless and connection oriented connection.
Why frame sorting is required?
What is meant by subnet?
What is meant by Gateway?
What is an IP address?
What is MAC address?
Why IP address is required when we have MAC address?
What is meant by port?
What are ephemerical port number and well known port numbers?
What is a socket?
What are the parameters of socket()?
Describe bind(), listen(), accept(),connect(), send() and recv().
What are system calls? Mention few of them.
What is IPC? Name three techniques.
Explain mkfifo(), open(), close() with parameters.
What is meant by file descriptor?
What is meant by traffic shaping?
How do you classify congestion control algorithms?
Differentiate between Leaky bucket and Token bucket.
How do you implement Leaky bucket?
How do you generate busty traffic?
What is the polynomial used in CRC-CCITT?
What are the other error detection algorithms?
What is difference between CRC and Hamming code?
Why Hamming code is called 7,4 code?
What is odd parity and even parity?
What is meant by syndrome?
What is generator matrix?
What is spanning tree?
Where Pirms algorithm does finds its use in Networks?
Differentiate between Prims and Kruskals algorithm.
What are Routing algorithms?
How do you classify routing algorithms? Give examples for each.
What are drawbacks in distance vector algorithm?
How routers update distances to each of its neighbor?
How do you overcome count to infinity problem?
What is cryptography?

Department Of Information Science and Engineering

Page 57

Computer Networks Lab Manual

51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.
73.
74.
75.
76.
77.
78.
79.

How do you classify cryptographic algorithms?


What is public key?
What is private key?
What are key, ciphertext and plaintext?
What is simulation?
What are advantages of simulation?
Differentiate between Simulation and Emulation.
What is meant by router?
What is meant by bridge?
What is meant by switch?
What is meant by hub?
Differentiate between route, bridge, switch and hub.
What is ping and telnet?
What is FTP?
What is BER?
What is meant by congestion window?
What is BSS?
What is incoming throughput and outgoing throughput?
What is collision?
How do you generate multiple traffics across different sender-receiver pairs?
How do you setup Ethernet LAN?
What is meant by mobile host?
What is meant by NCTUns?
What are dispatcher, coordinator and nctunsclient?
Name few other Network simulators
Differentiate between logical and physical address.
Which address gets affected if a system moves from one place to another place?
What is ICMP? What are uses of ICMP? Name few.
Which layer implements security for data?

Department Of Information Science and Engineering

Page 58

Computer Networks Lab Manual

Guidelines For installation of NCTUns Network Simulator

1.
2.
3.
4.

Follow the following steps carefully,


Please don't skip any steps that have been mentioned below
Install Linux
Recommended Fedora 12 with dvd(gcc compiler should be installed if it not installed
after fedora installation)
After installation Boot into Linux as root.
Copy the .tgz installation file of NCTUns that you got from college to the folder /bin/local
Please don't change any folder name in this folder that is created after unzipping the above
file. Dont even change the Case of the folder that is created
Now unzip the .tgz file by opening the terminal and changing the directory to /bin/local by
the command :[root@localhost ~] cd /bin/local
To unzip use the following command:[root@localhost local] tar xvzf [the file name].tar
(Note there is no '-' before xvzf)
This will create a folder called NCTUns in the directory /bin/local...

5.

Now disable the Secure Linux option by running the following command :[root@localhost local] vi /etc/selinux/config
When the file opens, there is a line similar to -- SELINUX=enforcing
Change the "enforcing" to "disabled" (Note without quotes)

6.

From the directory /bin/local change the current working directory to NCTUns by following
command :[root@localhost local] cd NCTUns

7.

Now from here execute the installation shell script that will do the required compilations
and settings for you:[root@localhost local] ./install.sh
During this part it will ask for installation of tunnel files. Please type yes and Enter to
continue

8.

If the installation is successful, it will display the success message at the end. Now restart
your computer. You will find a new entry in GRUB Menu "NCTUns kernel login". Boot
into Linux using this entry.

9.

before using simulator, please execute the following command


[root@localhost ~] iptables -F
Run the simulator using three commands where each command should be executed in
different window.
[root@localhost ~] dispatcher
[root@localhost ~] coordinator
[root@localhost ~] nctunsclient

10.

Department Of Information Science and Engineering

Page 59

Computer Networks Lab Manual

11.

In the NCTUns window Settings Dispatcher. Provide the username and password of the
user account u created in step 11. Then Click OK.

Department Of Information Science and Engineering

Page 60

Вам также может понравиться