0% found this document useful (0 votes)
24 views115 pages

Network Lab605

Uploaded by

abinesanthosh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
24 views115 pages

Network Lab605

Uploaded by

abinesanthosh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 115

SREE BUDDHA COLLEGE OF ENGINEERING, AYATHIL, ELAVUMTHITTA

PATHANAMTHITTA – 689625

LABORATORY RECORD

Certified that this is the bonafide work done by ……………………………………………………..

of Sixth Semester Computer science and Engineering branch in the CSL 332

Networking Lab Laboratory during 2022-2023.

Faculty in Charge

Register No: ………………………… Exam Date ……………

Internal Examiner External Examiner


INDEX
EXPT DATE NAME OF EXPERIMENT PAGE
NO NO
CSL 332 Networking Lab SBW20CS025

Experiment No : 1
Date :

Getting Started With The Basics Of Network Configuration Files And


Networking Commands In Linux

AIM: Familiarize and understand the basics of network configuration files and networking
commands in Linux

The important network configuration files in Linux operating systems are

1. /etc/hosts

This file is used to resolve hostnames on small networks with no DNS server. This text file contains
a mapping of an IP address to the corresponding host name in each line. This file also contains a
line specifying the IP address of the loopback device i.e, 127.0.0.1 is mapped to localhost.

A typical hosts file is as shown

127.0.0.1 localhost
127.0.1.1 nwlab4-desktop

2. /etc/resolv.conf

This configuration file contains the IP addresses of DNS servers and the search domain.

A sample file is shown

# DO NOT EDIT THIS FILE BY HAND -- YOUR CHANGES WILL BE OVERWRITTEN


nameserver 127.0.1.1

3. /etc/sysconfig/network

This configuration file specifies routing and host information for all network interfaces. It contains
directives that are global specific. For example if NETWORKING=yes, then /etc/init.d/network
activates network devices

Department of CSE, SBCE Page. 1


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 2


CSL 332 Networking Lab SBW20CS025

4. /etc/nsswitch.conf

This file includes database search entries. The directive specifies which database is to be searched
first.

The important Linux networking commands are

1. ifconfig

This command gives the configuration of all interfaces in the system.

It can be run with an interface name to get the details of the

interface. ifconfig wlan0


enp2s0 Link encap:Ethernet HWaddr 00:e0:4c:7a:2a:fa
inet addr:172.16.0.48 Bcast:172.16.0.255 Mask:255.255.255.0
inet6 addr: fe80::ee55:aab8:8c23:d471/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1492 Metric:1
RX packets:8048 errors:0 dropped:0 overruns:0 frame:0
TX packets:1620 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:3500014 (3.5 MB) TX bytes:138567 (138.5 KB)

lo Link encap:Local Loopback


inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:65536 Metric:1
RX packets:258 errors:0 dropped:0 overruns:0 frame:0
TX packets:258 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:21239 (21.2 KB) TX bytes:21239 (21.2 KB)

This gives the IP address, subnet mask, and broadcast address of the wireless LAN adapter. Also
tells that it can support multicasting.

If eth0 is given as the parameter, the command gives the details of the Ethernet adapter.

Department of CSE, SBCE Page. 3


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 4


CSL 332 Networking Lab SBW20CS025

2. netstat

This command command gives network status information.

netstat -i

Iface MTU Met RX-OK RX- RX-DRP RX-OVR TX-OK TX- TX- TX- Flg
ERR ERR DRP OVR
enp2s0 1492 0 6964 0 0 0 1597 0 0 0 BMRU
lo 6553 0 254 0 0 0 254 0 0 0 LRU

As shown above, the command with -i flag provides information on the interfaces. lo stands for
loopback interface.

3. ping

This is the most commonly used command for checking

connectivity. ping www.google.com

PING google.com (142.250.182.110) 56(84) bytes of data.


64 bytes from maa05s21-in-f14.1e100.net (142.250.182.110): icmp_seq=1 ttl=58 time=18.0
ms 64 bytes from maa05s21-in-f14.1e100.net (142.250.182.110): icmp_seq=2 ttl=58
time=18.1 ms 64 bytes from maa05s21-in-f14.1e100.net (142.250.182.110): icmp_seq=3
ttl=58 time=18.2 ms 64 bytes from maa05s21-in-f14.1e100.net (142.250.182.110):
icmp_seq=4 ttl=58 time=18.0 ms 64 bytes from maa05s21-in-f14.1e100.net
(142.250.182.110): icmp_seq=5 ttl=58 time=18.1 ms
--- google.com ping statistics ---
5 packets transmitted, 5 received, 0% packet loss, time 4005ms
rtt min/avg/max/mdev = 18.054/18.139/18.299/0.147 ms

A healthy connection is determined by a steady stream of replies with consistent times. Packet loss
is shown by discontinuity of sequence numbers. Large scale packet loss indicates problem along the
path

Department of CSE, SBCE Page. 5


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 6


CSL 332 Networking Lab SBW20CS025

RESULT
Familiarized and understood the basics of network configuration files and networking commands in
Linux

Department of CSE, SBCE Page. 7


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 8


CSL 332 Networking Lab SBW20CS025

Experiment No : 2
Date :

To Familiarize And Understand The Use And Functioning Of System Calls Used
For Network Programming In Linux

AIM: To familiarize and understand the use and functioning of system calls used for
network programming in Linux.

Some system calls of Linux operating systems


1. ps

This command tells which all processes are running on the system when ps runs.

ps -ef

UID PID PPID C STIME TTY TIME CMD


root 1 0 0 13:51 ? 00:00:01 /sbin/init splash
root 2 0 0 13:51 ? 00:00:00 [kthreadd]
root 4 2 0 13:51 ? 00:00:00 [kworker/0:0H]
root 6 2 0 13:51 ? 00:00:00 [mm_percpu_wq]
root 7 2 0 13:51 ? 00:00:00 [ksoftirqd/0]
root 8 2 0 13:51 ? 00:00:00 [rcu_sched]
root 9 2 0 13:51 ? 00:00:00 [rcu_bh]
root 10 2 0 13:51 ? 00:00:00 [migration/0]

This command gives processes running on the system, the owners of the processes and the names of
the processes. The above result is an abridged version of the output.

2. fork

This system call is used to create a new process. When a process makes a fork system call, a new
process is created which is identical to the process creating it. The process which calls fork is called
the parent process and the process that is created is called the child process. The child and parent
processes are identical, i.e, child gets a copy of the parent's data space, heap and stack, but have
different physical address spaces. Both processes start execution from the line next to fork. Fork
returns the process id of the child in the parent process and returns 0 in the child process

Department of CSE, SBCE Page. 9


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 10


CSL 332 Networking Lab SBW20CS025

#include<stdio.h> void main()


{
int pid;
pid = fork();
if(pid > 0)
{
printf (“ Iam parent\n”);
}
else
{
printf(“Iam child\n”);
}
}
The parent process prints the first statement and the child prints the next statement.

3. exec
New programs can be run using exec system call. When a process calls exec, the process is
completely replaced by the new program. The new program starts executing from its main function.
A new process is not created, process id remains the same, and the current process's text, data, heap,
and stack segments are replaced by the new program. exec has many flavours one of which is
execv.
execv takes two parameters. The first is the pathname of the program that is going to be executed.
The second is a pointer to an array of pointers that hold the addresses of arguments. These
arguments are the command line arguments for the new program.

4. wait
When a process terminates, its parent should receive some information reagarding the process like
the process id, the termination status, amount of CPU time taken etc. This is possible only if the
parent process waits for the termination of the child process. This waiting is done by calling the
wait system call. When the child process is running, the parent blocks when wait is called. If the
child terminates normally or abnormally, wait immedaitely returns with the termination status of the

Department of CSE, SBCE Page. 11


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 12


CSL 332 Networking Lab SBW20CS025

child. The wait system call takes a parameter which is a pointer to a location in which the
termination status is stored.

5. exit
When exit function is called, the process undergoes a normal termination.

6. open
This system call is used to open a file whose pathname is given as the first parameter of the
function. The second parameter gives the options that tell the way in which the file can be used.
open(filepathname , O_RDWR);
This causes the file to be read or written. The function returns the file descriptor of the file.

7. read
This system call is used to read data from an open file.
read(fd, buffer, sizeof(buffer));
The above function reads sizeof(buffer) bytes into the array named buffer. If the end of file is
encountered, 0 is returned, else the number of bytes read is returned.

8. write
Data is written to an open file using write function.
write(fd, buffer, sizeof(buffer));

System calls for network programming in Linux

1. Creating a socket
int socket (int domain, int type, int protocol);

This sytem call creates a socket and returns a socket descriptor. The domain parameter specifies a
communication domain; this selects the protocol family which will be used for communication.
These families are defined in . In this program the AF_INET family is used.

The type parameter indicates the communication semantics. SOCK_STREAM is used for tcp
connection while SOCK_DGRAM is used for udp connection. The protocol parameter specifies the
protocol used and is always 0. The header files used are <sys/types.h> and <sys/socket.h>

Department of CSE, SBCE Page. 13


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 14


CSL 332 Networking Lab SBW20CS025

RESULT
Familiarized and understood the use and functioning of system calls used for network
programming in Linux.

Department of CSE, SBCE Page. 15


CSL 332 Networking Lab SBW20CS025

CLIENT PROGRAM
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>

int main(int argc, char*argv[])


{
struct sockaddr_in server;
int sd;
char buffer[200];

if((sd=socket(AF_INET,SOCK_STREAM,0))<0)
{
perror("Socket failed:");
exit(1);
}
bzero(&server,sizeof(server));
server.sin_family=AF_INET;
server.sin_port=htons(atoi(argv[2]));
inet_pton(AF_INET,argv[1],&server.sin_addr);

Department of CSE, SBCE Page. 16


CSL 332 Networking Lab SBW20CS025

Experiment No : 3
Date :

Implement Client-Server Communication Using Socket Programming And TCP


As Transport Layer Protocol
AIM: Client sends a string to the server using tcp protocol. The server reverses the string and
returns it to the client, which then displays the reversed string.

Description:

Steps for creating a TCP connection by a client are:

1. Creation of client socket

int socket(int domain, int type, int protocol);

This function call creates a socket and returns a socket descriptor. The domain parameter specifies a
communication domain; this selects the protocol family which will be used for communication.
These families are defined in . In this program, the domain AF_INET is used. The socket has the
indicated type, which specifies the communication semantics. SOCK_STREAM type provides
sequenced, reliable, two-way, connection based byte streams. The protocol field specifies the
protocol used. We always use 0. If the system call is a failure, a -1 is returned. The header files used
are sys/types.h and sys/socket.h.

2. Filling the fields of the server address structure.

The socket address structure is of type struct sockaddr_in.

struct sockaddr_in {
u_short sin_family; u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8]; /*unused, always zero*/
};
struct in_addr
{ u_long s_addr;
};

Department of CSE, SBCE Page. 17


CSL 332 Networking Lab SBW20CS025

if(connect(sd,(struct sockaddr*)&server,sizeof(server))<0)
{
perror("Connection failed:");
exit(1);
}
fgets(buffer,sizeof(buffer),stdin);
buffer[strlen(buffer)-1]='\0';

write(sd,buffer,sizeof(buffer));
read(sd,buffer,sizeof(buffer));

printf("%s\n",buffer);
close(sd);
}

Department of CSE, SBCE Page. 18


CSL 332 Networking Lab SBW20CS025

The fields of the socket address structure are

sin_family which in our case is AF_INET

sin_port which is the port number where socket binds

sin_addr which is the IP address of the server machine The header file that is to be used is
netinet/in.h

Example
struct(sockaddr_in servaddr; servaddr.sin_family = AF_INET;server.sin_port = htnos(port_number);

Why htons is used ?

Numbers on different machines may be represented differently ( bigendian machines and little-
endian machines). In a little-endian machine the low order byte of an integer appears at the lower
address; in a big-endian machine instead the low order byte appears at the higher address. Network
order, the order in which numbers are sent on the internet is big-endian. It is necessary to ensure
that the right representation is used on each machine. Functions are used to convert from host to
network form before transmission- htons for short integers and htonl for long integers.

The value for servaddr.sin_addr is assigned using the following function

inet_pton(AF_INET, “IP_Address”, &servaddr.sin_addr);

The binary value of the dotted decimal IP address is stored in the field when the function returns.

3. Binding of the client socket to a local port

This is optional in the case of client and we usually do not use the bind function on the client side.

4. Connection of client to the server

A server is identified by an IP address and a port number. The connection operation is used on the
client side to identify and start the connection to the server.

int connect(int sd, struct sockaddr * addr, int addrlen);

Department of CSE, SBCE Page. 19


CSL 332 Networking Lab SBW20CS025

SERVER PROGRAM
#include<stdio.h>
#include<sys/types.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<unistd.h>

int main(int argc,char*argv[])


{
struct sockaddr_in server,cli;
int cli_len = sizeof(cli);
int sd,n,i,len;
int data,temp;

char buffer[100];
if((sd=socket(AF_INET,SOCK_STREAM,0)),0)
{
perror("Socket failed:");
exit(1);
}
bzero(&server,sizeof(server));
server.sin_family = AF_INET;
server.sin_port= htons(atoi(argv[1]));
server.sin_addr.s_addr=htonl(INADDR_ANY);

if(bind(sd,(struct sockaddr*)&server,sizeof(server))<0)
{

Department of CSE, SBCE Page. 20


CSL 332 Networking Lab SBW20CS025

sd – file descriptor of local socket


addr – pointer to protocol address of other socket addrlen – length in bytes of address structure

The header files to be used are sys/types.h and sys/socket.h It returns 0 on sucess and -1 in case of
failure.

5. Reading from socket


In the case of TCP connection reading from a socket can be done using the read system call

int read(int sd, char * buf, int length);

6. Writing to a socket

In the case of TCP connection writing to a socket can be done using the write system call

int write( int sd, char * buf, int length);

7. Closing the connection

The connection can be closed using the close system call

int close( int sd);

Steps for TCP Connection for server

1. Creating a listening socket

int socket( int domain, int type, int protocol);

This system call creates a socket and returns a socket descriptor. The domain field used is
AF_INET. The socket type is SOCK_STREAM. The protocol field is 0. If the system call is a
failure, a -1 is returned. Header files used are sys/types.h and sys/socket.h.

2. Binding to a local port

int bind(int sd, struct sockaddr * addr, int addrlen);

This call is used to specify for a socket the protocol port number where it will wait for messages. A
call to bind is optional on the client side, but required on the server side. The first field is the socket
descriptor of local socket. Second is a pointer to protocol address structure of this socket. The third

Department of CSE, SBCE Page. 21


CSL 332 Networking Lab SBW20CS025

perror("Bind failed");
exit(1);
}
listen(sd,5);

if((data=accept(sd,(struct sockaddr*)&cli,&cli_len))<0)
{
perror("Accept failed");
exit(1);
}
read(data,buffer,sizeof(buffer));
len = strlen(buffer);

for(i=0;i<len/2;i++)
{
temp = buffer[i];
buffer[i]=buffer[len-1-i];
buffer[len-1-i] = temp;
}
write(data,buffer,sizeof(buffer));
close(data);
close(sd);
}

Department of CSE, SBCE Page. 22


CSL 332 Networking Lab SBW20CS025

is the length in bytes of the structure referenced by addr. This system call returns an integer. It is 0
for success and -1 for failure. The header files are sys/types.h and sys/socket.h.

3. Listening on the port

The listen function is used on the server in the connection oriented communication to prepare a
socket to accept messages from clients.

int listen(int fd, int qlen);

fd – file descriptor of a socket that has already been bound

qlen – specifies the maximum number of messages that can wait to be processed by the server while
the server is busy servicing another request. Usually it is taken as 5. The header files used are
sys/types.h and sys/socket.h. This function returns 0 on success and -1 on failure.

4. Accepting a connection from the client

The accept function is used on the server in the case of connection oriented communication to
accept a connection request from a client.

int accept( int fd, struct sockaddr * addressp, int * addrlen);

The first field is the descriptor of server socket that is listening. The second parameter addressp
points to a socket address structure that will be filled by the address of calling client when the
function returns. The third parameter addrlen is an integer that will contain the actual length of
address structure of client. It returns an integer that is a descriptor of a new socket called the
connection socket. Server sockets send data and read data from this socket. The header files used
are sys/types.h and sys/socket.h.

Department of CSE, SBCE Page. 23


CSL 332 Networking Lab SBW20CS025

OUTPUT

Department of CSE, SBCE Page. 24


CSL 332 Networking Lab SBW20CS025

ALGORITHM
Client

1. Create socket

2. Connect the socket to the server

3. Read the string to be reversed from the standard input and send it to the server Read the matrices
from the standard input and send it to server using socket

4. Read the reversed string from the socket and display it on the standard output Read product
matrix from the socket and display it on the standard output

5. Close the socket

Server

1. Create listening socket

2. bind IP address and port number to the socket

3. listen for incoming requests on the listening socket

4. accept the incoming request

5. connection socket is created when accept returns

6. Read the string using the connection socket from the client

7. Reverse the string

8. Send the string to the client using the connection socket

9. close the connection socket

10. close the listening socket

Department of CSE, SBCE Page. 25


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 26


CSL 332 Networking Lab SBW20CS025

RESULT

Program to implement client-server communication using socket programming and TCP as


transport layer protocol has executed and output obtained successfully

Department of CSE, SBCE Page. 27


CSL 332 Networking Lab SBW20CS025

CLIENT PROGRAM

#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<netdb.h>
int main(int argc,char* argv[])
{
struct sockaddr_in server,client; if(argc!
=3)
printf("Input format not correct\n");
int sockfd=socket(AF_INET,SOCK_DGRAM,0);
if(sockfd==-1)
printf("Error in socket();");
server.sin_family = AF_INET;
server.sin_addr.s_addr=INADDR_ANY;
server.sin_port= htons(atoi(argv[2]));
char buffer[100];
printf("Enter a message to be sent to server\n");
fgets(buffer,100,stdin);
if(sendto(sockfd,buffer,sizeof(buffer),0,(struct sockaddr*)&server,sizeof(server))<0)
printf("Error in sendto");
return 0;
}

Department of CSE, SBCE Page. 28


CSL 332 Networking Lab SBW20CS025

Experiment No : 4
Date :

Implement Client-Server Communication Using Socket Programming And UDP


As Transport Layer Protocol

AIM: Client sends a message to the server using udp protocol. The server displays the message,
when it receives it to the client .

Description:

Steps for transfer of data using UDP

1. Creation of UDP socket

The function call for creating a UDP socket is

int socket(int domain, int type, int protocol);

The domain parameter specifies a communication domain; this selects the protocol family which
will be used for communication. These families are defined in . In this program, the domain
AF_INET is used. The next field type has the value SOCK_DGRAM. It supports datagrams
(connectionless, unreliable messages of a fixed maximum length). The protocol field specifies the
protocol used. We always use 0. If the socket function call is successful, a socket descriptor is
returned. Otherwise -1 is returned. The header files necessary for this function call are sys/types.h
and sys/socket.h.

2. Filling the fields of the server address structure.

The socket address structure is of type struct sockaddr_in.

struct sockaddr_in {
u_short sin_family; u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8]; /*unused, always zero*/
};

Department of CSE, SBCE Page. 29


CSL 332 Networking Lab SBW20CS025

SERVER PROGRAM

#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<stdlib.h>
#include<netdb.h>
int main(int argc,char* argv[])
{
struct sockaddr_in server,client; if(argc!
=2)
printf("Input format not correct ");
int sockfd=socket(AF_INET,SOCK_DGRAM,0);
if(sockfd==-1)
printf("Error in socket();");
server.sin_family=AF_INET;
server.sin_addr.s_addr=INADDR_ANY;
server.sin_port=htons(atoi(argv[1]));
if(bind(sockfd,(struct sockaddr*)&server,sizeof(server))<0)
printf("Error in blind()!\n");
char buffer[100];
socklen_t server_len =
sizeof(server); printf("Server
waiting............................");
if(recvfrom(sockfd,buffer,100,0,(struct sockaddr*)&server,&server_len)<0)
printf("Error in recvfrom()!");
printf("\nGot a datagram:%s",buffer);
return 0;
}

Department of CSE, SBCE Page. 30


CSL 332 Networking Lab SBW20CS025

struct in_addr {

u_long s_addr;

The fields of the socket address structure are

sin_family which in our case is AF_INET

sin_port which is the port number where socket binds

sin_addr is used to store the IP address of the server machine and is of type struct in_addr

The header file that is to be used is netinet/in.h

The value for servaddr.sin_addr is assigned using the following function

inet_pton(AF_INET, “IP_Address”, &servaddr.sin_addr);

The binary value of the dotted decimal IP address is stored in the field when the function returns.

3. Binding of a port to the socket in the case of server

This call is used to specify for a socket the protocol port number where it will wait for messages. A
call to bind is optional in the case of client and compulsory on the server side.

int bind(int sd, struct sockaddr* addr, int addrlen);

The first field is the socket descriptor. The second is a pointer to the address structure of this
socket. The third field is the length in bytes of the size of the structure referenced by addr. The
header files are sys/types.h and sys/socket.h. This function call returns an integer, which is 0 for
success and -1 for failure.

4. Receiving data

ssize_t recvfrom(int s, void * buf, size_t len, int flags, struct sockaddr * from, socklen_t *
fromlen);

The recvfrom calls are used to receive messages from a socket, and may be used to receive data
on a socket whether or not it is connection oriented. The first parameter s is the socket descriptor to
read from. The second parameter buf is the buffer to read information into. The third parameter len

Department of CSE, SBCE Page. 31


CSL 332 Networking Lab SBW20CS025

OUTPUT

Department of CSE, SBCE Page. 32


CSL 332 Networking Lab SBW20CS025

is the maximum length of the buffer. The fourth parameter is flag. It is set to zero. The fifth
parameter from is a pointer to struct sockaddr variable that will be filled with the IP address and
port of the orginating machine. The sixth parameter fromlen is a pointer to a local int variable that
should be initialized to sizeof(struct sockaddr). When the function returns, the integer variable that
fromlen points to will contain the actual number of bytes that is contained in the socket address
structure. The header files required are sys/types.h and sys/socket.h. When the function returns, the
number of bytes received is returned or -1 if there is an error.

5. Sending data
sendto- sends a message from a socket
ssize_t sendto(int s, const void * buf, size_t len, int flags, const struct sockaddr * to, socklen_t
tolen);

The first parameter s is the socket descriptor of the sending socket. The second parameter buf is the
array which stores data that is to be sent. The third parameter len is the length of that data in bytes.
The fourth parameter is the flag parameter. It is set to zero. The fifth parameter to points to a
variable that contains the destination IP address and port. The sixth parameter tolen is set to
sizeof(struct sockaddr). This function returns the number of bytes actually sent or -1 on error. The
header files used are sys/types.h and sys/socket.h

Department of CSE, SBCE Page. 33


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 34


CSL 332 Networking Lab SBW20CS025

ALGORITHM
Client

1. Create socket

2. Read the message from the standard input and send it to server using socket

3. Close the socket Server

Server

1. Create socket

2. bind IP address and port number to the socket

3. Read the message from the client using socket

4. Display the message through the standard output

5. close the socket

RESULT
Program to implement client-server communication using socket programming and UDP as

transport layer protocol has executed and output obtained successfully

Department of CSE, SBCE Page. 35


CSL 332 Networking Lab SBW20CS025

CLIENT PROGRAM

#include<stdio.h>
#include<sys/socket.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<pthread.h>
char msg[500];
void *recvmg(void *my_sock)
{
int sock = *((int*)my_sock);
int len;
//client thread always ready to recieve message
while((len=recv(sock,msg,500,0))>0)
{
msg[len] = '\0';
fputs(msg,stdout);
}
}
int main(int argc,char *argv[])
{
pthread_t recvt;
int len;
int sock;
char send_msg[500];
struct sockaddr_in ServerIp;
char client_name[100];
strcpy(client_name,argv[1]);
sock =
socket(AF_INET,SOCK_STREAM,0);
ServerIp.sin_port = htons(1234);
ServerIp.sin_family=AF_INET;

Department of CSE, SBCE Page. 36


CSL 332 Networking Lab SBW20CS025

Experiment No : 5
Date :
Implementation Of A Multi User Chat Server Using TCP As Transport Layer
Protocol

AIM:To implement a chat server so that multiple users can chat simultaneously

ALGORITHM
Client
1. Get client name.
2. Create client socket.
3. Send connection request.
4. Create client thread which is always waiting receive message.
5. Read message from console.
6. Write message to server socket.
7. Create receive function which receive and print message.

Server

1. Create socket
2. Bind
3. Listen
4. Accept connection
5. Create thread for each client.
6. Create function receive message from client.
7. Create fuction to send message to all clients.

Department of CSE, SBCE Page. 37


CSL 332 Networking Lab SBW20CS025

ServerIp.sin_addr.s_addr = inet_addr("127.0.0.1"); if((connect(sock,


(struct sockaddr*)&ServerIp,sizeof(ServerIp)))==-1)
printf("\nConnection to socket failed\n");
//creating a client thread which is always waiting for a message pthread_create(&recvt,NULL,
(void*)recvmg,&sock);
//ready to read a message from console
while(fgets(msg,500,stdin)>0)
{
strcpy(send_msg,client_name);
strcat(send_msg,":");
strcat(send_msg,msg);
len=write(sock,send_msg,strlen(send_msg));
if(len<0)
printf("\nMessage not sent\n");
}
//thread closed
pthread_join(recvt,NULL);
close(sock);
return 0;
}

SERVER PROGRAM

#include<stdio.h>
#include<sys/socket.h>
#include<string.h>
#include<arpa/inet.h>
#include<unistd.h>
int main()

Department of CSE, SBCE Page. 38


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 39


CSL 332 Networking Lab SBW20CS025

int sock=0,client_conn=0,counter=0,pid;
char data_send[1024],data_received[1024];
struct sockaddr_in ServerIp;
sock=socket(AF_INET,SOCK_STREAM,0);
memset(&ServerIp,'0',sizeof(ServerIp));
ServerIp.sin_family=AF_INET;
ServerIp.sin_port = htons(1234);
ServerIp.sin_addr.s_addr= inet_addr("127.0.0.1"); if(bind(sock,
(struct sockaddr*)&ServerIp,sizeof(ServerIp))==-1)
printf("\nSocket binding
failed"); if(listen(sock,20)==-1)
printf("Error\n");
else
printf("\nServer started\n");
for(;;)
{
label1:
client_conn= accept(sock,(struct sockaddr*)NULL,NULL);
pid= fork();
if(pid<0)
printf("Process creation failed");
else if(pid>0)
{
counter++;
//close(client_conn);
goto label1;
}
else
{
counter++;
if(recv(client_conn,data_received,1024,0)==-1)

Department of CSE, SBCE Page. 40


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 41


CSL 332 Networking Lab SBW20CS025

printf("Error!!cannot get response\n");


printf("Data from client is %s",data_received);
sprintf(data_send,"Hi client %d !!from server",counter);
write(client_conn,data_send,sizeof(data_send));
}
}
close(sock);
return 0;
}

OUTPUT

Department of CSE, SBCE Page. 42


CSL 332 Networking Lab SBW20CS025

RESULT
Program to implement a chat server so that multiple users can chat simultaneously has been
executed and output obtained successfully

Department of CSE, SBCE Page. 43


CSL 332 Networking Lab SBW20CS025

CLIENT PROGRAM

#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<unistd.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<time.h>

#define MAXLINE 1024


#define LISTENQ 10
typedef struct sockaddr SA;
int main(int argc,char **argv)
{
int sockfd,n;
char recvline[MAXLINE +1];
struct sockaddr_in servaddr;
int port;
if(argc!=3)
{
printf("Usage:a.out<IPaddress><port no.>");
}
if((sockfd= socket(AF_INET,SOCK_STREAM,0))<0) //Creates a TCP socket
{
printf("Socket Error");
}
port = atoi(argv[2]); //ascii to integer converstion
bzero(&servaddr,sizeof(servaddr)); //fill servaddr with zeros

Department of CSE, SBCE Page. 44


CSL 332 Networking Lab SBW20CS025

Experiment No : 6
Date :
Implementation Of A Concurrent Time Server Using UDP
AIM: Client sends a time request to the server, server sends its system time back to the client.

Description:

A concurrent server handles multiple clients at the same time. The simplest technique for a
concurrent server is to call the Unix fork function, i.e; creating one child process for each client.
The current time and date is obtained by the library function time which returns the number of
seconds since the Unix Epoch: 00:00:00 January 1, 1970, UTC (Coordinated Universal Time).
ctime is a function that converts this integer value into a human readable string.

ALGORITHM

Client
1. Create UDP socket
2. Send a request for time to the server
3. Receive the time from the server
4. Display the result

Server

1. Create a UDP socket


2. bind the port and address to the socket
3. while (1)
3.1 Receive time request from the client
3.2 create a child process using fork
If child process
3.2.1 Use time and ctime functions to find out cuurent time
3.2.2 Send the time as a string to the client
3.2.3 Exit
4. end of while

Department of CSE, SBCE Page. 45


CSL 332 Networking Lab SBW20CS025

servaddr.sin_family =AF_INET;
servaddr.sin_port =htons(port);
if(inet_pton(AF_INET,argv[1],&servaddr.sin_addr)<=0)
{
printf("inet_pton error for %s",argv[1]);
}
if(connect(sockfd,(struct sockaddr*)&servaddr,sizeof(servaddr))<0)
{
printf("Connect Error.\n");
}
while((n=read(sockfd,recvline,MAXLINE))>0) //reads server reply
{
recvline[n] =0;
if(fputs(recvline,stdout)==EOF)
{
printf("fputs error./n");
}
}
if(n<0)
{
printf("Read error");
}
}

SERVER PROGRAM

#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<stdlib.h>

Department of CSE, SBCE Page. 46


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 47


CSL 332 Networking Lab SBW20CS025

#include<unistd.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<time.h>

#define MAXLINE 1024


#define LISTENQ 10
typedef struct sockaddr SA;
int main(int argc,char **argv)
{
int listenfd,connfd;
struct sockaddr_in servaddr,cliaddr;
char buff[MAXLINE];
time_t ticks;
int port;
socklen_t len;

listenfd = socket(AF_INET,SOCK_STREAM,0); //CREATE A TCP SOCKET

port = atoi(argv[1]);
bzero(&servaddr,sizeof(servaddr)); //fill servaddr with zeros
servaddr.sin_family =AF_INET;
servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
servaddr.sin_port =htons(port);

bind(listenfd,(SA*)&servaddr,sizeof(servaddr));
printf("Server is waiting connection at port %d\t\n",port);
listen(listenfd,LISTENQ);
for(;;)
{

Department of CSE, SBCE Page. 48


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 49


CSL 332 Networking Lab SBW20CS025

len = sizeof(cliaddr);
connfd = accept(listenfd,(SA*)&cliaddr,&len);
printf("Connection from %s,port %d\
n",inet_ntop(AF_INET,&cliaddr.sin_addr.s_addr,buff,sizeof(buff)),ntohs(cliaddr.sin_port));
ticks = time(NULL);
snprintf(buff,sizeof(buff),"%.24s\r\n",ctime(&ticks));
write(connfd,buff,strlen(buff));
close(connfd);
}
}

OUTPUT

Department of CSE, SBCE Page. 50


CSL 332 Networking Lab SBW20CS025

RESULT
Program to implement a concurrent time server using UDP has been executed and output obtained
successfully

Department of CSE, SBCE Page. 51


CSL 332 Networking Lab SBW20CS025

CLIENT PROGRAM
#include<stdio.h>
#include<stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
typedef struct
packet{ char
data[1024];
}Packet;
typedef struct frame{
int frame_kind; //ACK:0, SEQ:1 FIN:2
int sq_no;
int ack;
Packet packet;
}Frame;
int main(int argc,char *argv[]){
if (argc != 2){
printf("Usage: %s<port>",argv[0]);
exit(0);
}
int port = atoi(argv[1]);
int sockfd;
struct sockaddr_in serverAddr;
char buffer[1024];
socklen_t addr_size;
int frame_id = 0;
Frame frame_send;
Frame frame_recv;
int ack_recv = 1;
sockfd = socket(AF_INET, SOCK_DGRAM, 0);

Department of CSE, SBCE Page. 52


CSL 332 Networking Lab SBW20CS025

Experiment No : 7
Date :
Stop And Wait

AIM: To write a program to simulate stop – and – wait protocol.

Description of Stop-and-Wait Protocol

Stop-and-wait Protocol is a flow control protocol used in the data link layer for transmission of data
in noiseless channels. Sender keeps on sending messages to the Receiver. In order to prevent the
receiver from overwhelming, there is a need to tell the sender to slow down the transmission of
frames. We can make use of feedback from the receiver to the sender. Frames 0 sends to receiver,
ACK 1 will be sentback to sender; frame 1 goes to receiver, ACK 0 will be back to sender, and so
on

ALGORITHM
Client
while(true) //Repeat forever
canSend=true //It will allow the first frame to go.
{
WaitForEvent(); //sleep until the occurrence of an
event if(Event(RequestToSend) AND canSend) {
GetData();
MakeFrame();
SendFrame(); //Send the data frame
canSend=false; //cannot send until the acknowledgement arrives.
}
WaitForEvent(); //sleep until the occurrence of an event
if(Event(ArrivalNotification)) //indicates the arrival of the
acknowledgement
{
ReceiveFrame(); //Means the ACK frame received
canSend=true;
}
}

Department of CSE, SBCE Page. 53


CSL 332 Networking Lab SBW20CS025

memset(&serverAddr, '\0', sizeof(serverAddr));


serverAddr.sin_family = AF_INET;serverAddr.sin_port = htons(port);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
while(1){
if(ack_recv == 1){
frame_send.sq_no = frame_id;
frame_send.frame_kind = 1;
frame_send.ack = 0;
printf("Enter Data: ");
scanf("%s", buffer);
strcpy(frame_send.packet.data, buffer);
sendto(sockfd, &frame_send, sizeof(Frame), 0, (struct sockaddr*)&serverAddr,
sizeof(serverAddr));
printf("[+]Frame Send\n");
}
int addr_size = sizeof(serverAddr);
int f_recv_size = recvfrom(sockfd, &frame_recv, sizeof(frame_recv), 0 ,(struct
sockaddr*)&serverAddr, &addr_size);
if(f_recv_size > 0 && frame_recv.sq_no == 0 && frame_recv.ack ==frame_id+1)
{ printf("[+]Ack Received\n");
ack_recv = 1;
}else{
printf("[-]Ack Not Received\n");
ack_recv = 0;
}
frame_id++;
}
close(sockfd);
return 0;
}

Department of CSE, SBCE Page. 54


CSL 332 Networking Lab SBW20CS025

Server

while(true) //means Repeat forever


{
WaitForEvent(); //sleep until the occurrence of an event
if(Event(ArrivalNotification)) //indicates arrival of the data
frame
{
ReceiveFrame();
ExtractData();
Deliver(data); //delivers the data to the network
layer. SendFrame(); //Send the ACK frame
}
}

Department of CSE, SBCE Page. 55


CSL 332 Networking Lab SBW20CS025

SERVER PROGRAM
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#include<sys/types.h>
#include<sys/stat.h>
#include <sys/socket.h>
#include<unistd.h>
#include<arpa/inet.h>
typedef struct
packet{ char
data[1024];
}Packet;
typedef struct frame{
int frame_kind;
int sq_no;
int ack;
Packet packet;
}Frame;
int main(int argc, char** argv){
if (argc != 2){
printf("Usage: %s <port>", argv[0]);
exit(0);
}
int port = atoi(argv[1]);
int sockfd;
struct sockaddr_in serverAddr, newAddr;
char buffer[1024];
socklen_t addr_size;
int frame_id=0;
Frame frame_recv;

Department of CSE, SBCE Page. 56


CSL 332 Networking Lab SBW20CS025
Frame frame_send;

Department of CSE, SBCE Page. 57


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 58


CSL 332 Networking Lab SBW20CS025

sockfd = socket(AF_INET, SOCK_DGRAM, 0);


memset(&serverAddr, '\0', sizeof(serverAddr));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(port);
serverAddr.sin_addr.s_addr = inet_addr("127.0.0.1");
bind(sockfd,(struct sockaddr*)&serverAddr,
sizeof(serverAddr)); addr_size = sizeof(newAddr);
while(1){
int f_recv_size =recvfrom(sockfd,&frame_recv,sizeof(Frame),0,(struct
sockaddr*)&newAddr, &addr_size);
if (f_recv_size > 0 && frame_recv.frame_kind == 1 && frame_recv.sq_no == frame_id)
{ printf("[+]Frame Received: %s\n", frame_recv.packet.data);
frame_send.sq_no = 0;
frame_send.frame_kind = 0;
frame_send.ack = frame_recv.sq_no + 1;
sendto(sockfd, &frame_send, sizeof(frame_send), 0, (struct sockaddr*)&newAddr, addr_size);
printf("[+]Ack Send\n");
}else{
printf("[+]Frame Not Received\n"); }
frame_id++;
}
close(sockfd);
return 0;
}

Department of CSE, SBCE Page. 59


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 60


CSL 332 Networking Lab SBW20CS025

OUTPUT

Department of CSE, SBCE Page. 61


CSL 332 Networking Lab SBW20CS025

RESULT
Program to to simulate stop – and – wait protocol has been executed and output obtained
successfully

Department of CSE, SBCE Page. 62


CSL 332 Networking Lab SBW20CS025

PROGRAM

#include<stdio.h>
#include<time.h>
#include<stdlib.h>
int main()
{
int nf,N;
int tr=0;
srand(time(NULL));
printf("Enter the number of frames :");
scanf("%d",&nf);
printf("Enter the number Window Size:");
scanf("%d",&N);
int i=1;
while(i<=nf)
{
int x=0;
for(int j=i;j<i+N&&j<=nf;j++)
{
printf("Sent Frame %d\n",j);
tr++;
}
for(int j=i;j<i+N&&j<=nf;j++)
{
int flag = rand()%2; if(!
flag)
{
printf("%d:Acknowleged!\n",j);
x++;
}
else
{
printf("Frames %d Not Received \n",j);
printf("Retransmitting Window \n");
break;
}
}

Department of CSE, SBCE Page. 63


CSL 332 Networking Lab SBW20CS025

Experiment No : 8
Date :
Go-Back-N

AIM: Write a program to perform simulation on sliding window protocol using Go-back-N ARQ

Description:-

Go-Back-N ARQ is mainly a specific instance of Automatic Repeat Request (ARQ) protocol where
the sending process continues to send a number of frames as specified by the window size even
without receiving an acknowledgement (ACK) packet from the receiver. The sender keeps a copy of
each frame until the acknowledgement arrives.

This protocol is a practical approach to the sliding window.

• In Go-Back-N ARQ, the size of the sender window is N and the size of the receiver
window is always 1.

• This protocol makes the use of cumulative acknowledgements means here the
receiver maintains an acknowledgement timer.

• If the receiver receives a corrupted frame, then it silently discards that corrupted frame
and the correct frame is retransmitted by the sender after the timeout timer expires.

• In case if the receiver receives the out of order frame then it simply discards all the frames.

• In case if the sender does not receive any acknowledgement then the frames in the
entire window will be retransmitted again.

Disadvantages

• Timeout timer runs at the receiver side only.

• The transmitter needs to store the last N packets.

• The retransmission of many error-free packets follows an erroneous packet.

Department of CSE, SBCE Page. 64


CSL 332 Networking Lab SBW20CS025

printf("\n");
i+=x;
}
printf("Total number of tramissions :%d\n",tr);
return 0;
}

OUTPUT

Department of CSE, SBCE Page. 65


CSL 332 Networking Lab SBW20CS025

RESULT
Program to perform simulation on sliding window protocol using Go-back-N ARQ has
been executed and output obtained successfully

Department of CSE, SBCE Page. 66


CSL 332 Networking Lab SBW20CS025

CLIENT PROGRAM

#include<sys/socket.h>
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>

int isfaulty(){
int d=rand()%4;
return(d>2);
}

int main(){
srand(time(0));
int c_sock;
c_sock=socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in client;
memset(&client,0,sizeof(client));
client.sin_family=AF_INET;
client.sin_port=htons(9009);
client.sin_addr.s_addr=inet_addr("127.0.0.1");
if(connect(c_sock,(struct sockaddr*)&client,sizeof(client))==-1)
{
printf("connection failed");
return 0;
}
printf("\n\tClient with individual acknowledgment scheme\n\n");
char msg1[50]="acknowledgement of";

Department of CSE, SBCE Page. 67


CSL 332 Networking Lab SBW20CS025

Experiment No : 9
Date :

Selective Repeat

AIM: To simulate selective repeat protocol.

Selective repeat protocol, also called Selective Repeat ARQ (Automatic Repeat reQuest), is a data
link layer protocol that uses sliding window method for reliable delivery of data frames. Here, only
the erroneous or lost frames are retransmitted, while the good frames are received and buffered.

It uses two windows of equal size: a sending window that stores the frames to be sent and a
receiving window that stores the frames receive by the receiver. The size is half the maximum
sequence number of the frame. For example, if the sequence number is from 0 – 15, the window
size will be 8.

Working Principle

Selective Repeat protocol provides for sending multiple frames depending upon the availability of
frames in the sending window, even if it does not receive acknowledgement for any frame in the
interim. The maximum number of frames that can be sent depends upon the size of the sending
window.

The receiver records the sequence number of the earliest incorrect or un-received frame. It then fills
the receiving window with the subsequent frames that it has received. It sends the sequence number
of the missing frame along with every acknowledgement frame.

The sender continues to send frames that are in its sending window. Once, it has sent all the frames
in the window, it retransmits the frame whose sequence number is given by the acknowledgements.
It then continues sending the other frames.

The control variables in Selective Repeat ARQ are same as in Go-Back-N ARQ: SF, SL and S. But
the sender sliding window size changed into 2m-1 .Receiver sliding window has 2 control variables,
RF and RL.

Department of CSE, SBCE Page. 68


CSL 332 Networking Lab SBW20CS025

char msg3[50]="negative ack";


char msg2[50];
char buff[100];
int count=-1,flag=1;
while(count<8)
{
bzero(buff,sizeof(buff));
bzero(msg2,sizeof(msg2));
if(count==7&&flag==1)
{
printf("here\n");
flag=0;
read(c_sock,buff,sizeof(buff));
continue;
}
int n=read(c_sock,buff,sizeof(buff));
char i=buff[strlen(buff)-1];
printf("message received from server:%s\n",buff);
int isfault=isfaulty();
printf("corruption status :%d\n",isfault);
printf("response/acknowledgement sent for message\n");
if(isfault)
strcpy(msg2,msg3);
else
{
strcpy(msg2,msg1);
count++;
}
msg2[strlen(msg2)]=i;
write(c_sock,msg2,sizeof(msg2));
}
}

Department of CSE, SBCE Page. 69


CSL 332 Networking Lab SBW20CS025

ALGORITHM

CLIENT

begin
frame s; //s denotes frame to be
sent frame t; //t is
temporary frame
S_window = power(2,m-1); //Assign maximum window size
SeqFirst = 0; // Sequence number of first frame in window
SeqN = 0; // Sequence number of Nth frame window
while (true) //check repeatedly
do
Wait_For_Event(); //wait for availability of
packet if ( Event(Request_For_Transfer)) then
if (SeqN–SeqFirst >= S_window) then
doNothing();
end if;
Get_Data_From_Network_Layer();
s = Make_Frame();
s.seq = SeqN;
Store_Copy_Frame(s);
Send_Frame(s);
Start_Timer(s);
SeqN = SeqN + 1;
end if;
if ( Event(Frame_Arrival) then
r = Receive_Acknowledgement();
//Resend frame whose sequence number is with
ACK if ( r.type = NAK) then
if ( NAK_No > SeqFirst && NAK_No < SeqN ) then
Retransmit( s.seq(NAK_No));
Start_Timer(s);
end if
//Remove frames from sending window with positive
ACK else if ( r.type = ACK ) then
Remove_Frame(s.seq(SeqFirst));
Stop_Timer(s);
SeqFirst = SeqFirst + 1;
end if
end if

Department of CSE, SBCE Page. 70


CSL 332 Networking Lab SBW20CS025

SERVER PROGRAM

#include<stdio.h>
#include<stdlib.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<sys/time.h>
#include<netinet/in.h>
#include<string.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<fcntl.h>

void rsendd(int ch,int c_sock){


char buff2[60];
bzero(buff2,sizeof(buff2));
strcpy(buff2,"reserver
message:");
buff2[strlen(buff2)]=(ch)+'0';
buff2[strlen(buff2)]='\0';
printf("Resending Message to client:%s\n",buff2);
write(c_sock,buff2,sizeof(buff2));
usleep(1000);
}

int main() {
int s_sock,c_sock;s_sock=socket(AF_INET,SOCK_STREAM,0);
struct sockaddr_in server,other;
memset(&server,0,sizeof(server));
memset(&other,0,sizeof(other));
server.sin_family=AF_INET;
server.sin_port=htons(9009);
server.sin_addr.s_addr=INADDR_ANY;

Department of CSE, SBCE Page. 71


CSL 332 Networking Lab SBW20CS025

// Resend frame if acknowledgement haven’t been received


if ( Event(Time_Out)) then
Start_Timer(s);
Retransmit_Frame(s);
end if end

SERVER
Begin
frame f;
RSeqNo = 0; // Initialise sequence number of expected
frame NAKsent = false;
ACK = false;
For each slot in receive_window
Mark(slot)=false;
while (true) //check repeatedly do Wait_For_Event(); //wait for arrival of
frame if ( Event(Frame_Arrival) then
Receive_Frame_From_Physical_Layer();
if ( Corrupted ( f.SeqNo ) AND NAKsent = false) then
SendNAK(f.SeqNo);
printf("\tServer Up\n Selective repeat scheme\n\n");
NAKsent = true;
end if
if ( f.SeqNo != RSeqNo AND NAKsent = false ) then
SendNAK(f.SeqNo);
NAKsent = true;
if ( f.SeqNo is in receive_window ) then
if ( Mark(RSeqNo) = false ) then
Store_frame(f.SeqNo);
Mark(RSeqNo) = true;
end if
end if
else
while ( Mark(RSeqNo))
Extract_Data(RSeqNo);
Deliver_Data_To_Network_Layer();
RSeqNo = RSeqNo + 1;
Send_ACK(RSeqNo);

Department of CSE, SBCE Page. 72


CSL 332 Networking Lab SBW20CS025

socklen_t add;
if(bind(s_sock,(struct sockaddr*)&server,sizeof(server))==-1){
printf("Binding failed\n");
return 0;
}
listen(s_sock,10);
add=sizeof(other);
c_sock=accept(s_sock,(struct sockaddr*)&other,&add);
time_t t1,t2;
char msg[50]="server message:";
char buff[50];
int flag=0;
fd_set set1,set2,set3;
struct timeval timeout1,timeout2,timeout3;int rv1,rv2,rv3;
int tot=0;
int ok[20];
memset(ok,0,sizeof(ok));
while(tot<9){
int toti=tot;
for(int j=(0+toti);j<(3+toti);j++){
bzero(buff,sizeof(buff));
char buff2[60];
bzero(buff2,sizeof(buff2));
strcpy(buff2,"server message:");
buff2[strlen(buff2)]=(j)+'0';
buff2[strlen(buff2)]='\0';
printf("Message sent to client:%s\t%d\t%d\n",buff2,tot,j);
write(c_sock,buff2,sizeof(buff2));
usleep(1000);
}
for(int k=0+toti;k<(toti+3);k++){
qq:

Department of CSE, SBCE Page. 73


CSL 332 Networking Lab SBW20CS025

end while
end if
end if
end while
end

Department of CSE, SBCE Page. 74


CSL 332 Networking Lab SBW20CS025

FD_ZERO(&set1);
FD_SET(c_sock,&set1);
timeout1.tv_sec=2;
timeout1.tv_usec=0;rv1=select(c_sock+1,&set1,NULL,NULL,&timeout1);
if(rv1==-1)
perror("select error");
else if(rv1==0){
printf("Timeout for message:%d\n",k);
rsendd(k,c_sock);
goto qq;}
else{
read(c_sock,buff,sizeof(buff));
printf("Message from client:%s\n",buff);
if(buff[0]=='n'){
printf("corrupt message acknowledgement(msg %d)\n",buff[strlen(buff)-
1]-'0'); rsendd((buff[strlen(buff)-1]-'0'),c_sock);
goto qq;}
else
tot++;
}
}
}
close(c_sock);
close(s_sock);
return 0;
}

Department of CSE, SBCE Page. 75


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 76


CSL 332 Networking Lab SBW20CS025

OUTPUT

Department of CSE, SBCE Page. 77


CSL 332 Networking Lab SBW20CS025

RESULT
Program to simulate selective repeat protocol has been executed and output obtained successfully

Department of CSE, SBCE Page. 78


CSL 332 Networking Lab SBW20CS025

PROGRAM
#include<stdio.h>
struct node
{
unsigned dist[20];
unsigned from[20];
}rt[10];

int main()
{
int costmat[20][20];
int
nodes,i,j,k,count=0;
printf("\nEnter the number of nodes:");
scanf("%d",&nodes);
printf("\nEnter the cost matrix:\n");
for(i=0;i<nodes;i++)
{
for(j=0;j<nodes;j++)
{
scanf("%d",&costmat[i][j]); costmat[i]
[i]=0; rt[i].dist[j]=costmat[i][j];
rt[i].from[j]=j;
}
}
do
{
count =0; for(i=0;i<nodes;i+
+) for(j=0;j<nodes;j++)
for(k=0;k<nodes;k++)

Department of CSE, SBCE Page. 79


CSL 332 Networking Lab SBW20CS025

Experiment No : 10
Date :

Implementation of distance vector (old ARPANET) routing algorithm

AIM: To implement distance vector routing algorithm, to compute shortest distance between each
node and its neighbouring nodes, and to update the distance (or cost) to reach its Neighbors.

Problem Definition:-

A distance-vector routing protocol requires that a router informs its neighbors of topology changes /
updates periodically. The term distance vector refers to the fact that protocol manipulates vectors
(arrays) of distances to other nodes in the network. "Distance" is a measure of the cost to reach a
certain node.

This algorithm is used in Routing Information Protocol (RIP) to calculate the direction and least-
cost distance (usually hop count) to any link in a network. Routers using distance-vector routing
protocol do not have the knowledge of entire path to a destination. Instead they use two methods:

1. Direction in which router or exit interface a packet should be forwarded.

2. Distance from its destination

Information kept by DV router -

-Each router has an ID

-Associated with each link connected to a router, there is a link cost (static or dynamic).

-Intermediate hops

Distance Vector Table Initialization -

Distance to itself = 0

Distance to ALL other routers = infinity number or a finite cost (distance) value based on hop count.

Distance Vector Algorithm –

-A router transmits its distance vector to each of its neighbors in a routing packet.

-Each router receives and saves the most recently received distance vector from each of its
neighbors.

Department of CSE, SBCE Page. 80


CSL 332 Networking Lab SBW20CS025

if(rt[i].dist[j]>costmat[i][k]+rt[k].dist[j])
{
rt[i].dist[j]=rt[i].dist[k]+rt[k].dist[j];
rt[i].from[j]=1;
count++;
}
}
while(count!=0);
for(i=0;i<nodes;i++)
{
printf("\n\nFor router %d\n",i+1);
for(j=0;j<nodes;j++)
{
printf("\t\nnode %d via %d Distance %d",j+1,rt[i].from[j]+1,rt[i].dist[j]);
}
}
printf("\n\n");
}

OUTPUT

Department of CSE, SBCE Page. 81


CSL 332 Networking Lab SBW20CS025

-A router recalculates its distance vector when:

It receives a distance vector from a neighbour containing different information than before.

It discovers that a link to a neighbour has gone down.

The DV calculation is based on minimizing the cost to each destination

Dx(y) = Estimate of least cost from x to y

C(x,v) = Node x knows cost to each neighbor v

Dx = [Dx(y): y ∈ N ] = Node x maintains distance vector


Node x also maintains its neighbors' distance vectors

– For each neighbor v, x maintains Dv = [Dv(y): y ∈ N ]

RESULT
Program to implement distance vector routing algorithm, to compute shortest distance between
each node and its neighbouring nodes, and to update the distance (or cost) to reach its Neighbors
has been executed and output obtained successfully

Department of CSE, SBCE Page. 82


CSL 332 Networking Lab SBW20CS025

PROGRAM
#include<stdio.h>
void shortest_path(int n,int cost[n][n],int src)
{
int dist[n];
int
visited[n];
int i;
int last[n];
int count;
for(i=0;i<n;i++)
{
dist[i] = 1000;
visited[i] =0;
last[i]=src;
}
dist[src]=0;
for(count =0;count<n-1;count++)
{
int min=1000;
int u;
for(i=0;i<n;i++)
{
if(visited[i]==0&&dist[i]<=min)
{
min=dist[i];
u=i;
}
}
visited[u]=1;
for(i=0;i<n;i++)
{

Department of CSE, SBCE Page. 83


CSL 332 Networking Lab SBW20CS025

Experiment No : 11
Date :

Link State Routing

AIM: To implement and simulate link state protocol

Description:

Routing algorithms can be classified as global or centralized. A global routing algorithm computes
the least cost path between a source and destination using knowledge about the entire network.
Global algorithm has complete information about connectivity and link costs. Such algorithms are
called link state algorithms.

ALGORITHM:

It is the Dijkstra algorithm. This algorithm finds the shortest (least cost paths) from the source u to
every other node in the network.

D(v) : cost of the least cost path from the source node to the destination node v as of this iteration of
the algorithm

p(v): previous node of v along the current least cost path from the source to v

N' : subset of nodes. v is in N' if the least cost path from the source to v is definitely known
Iniltialization :
N' = {u}

for all nodes v

if v is a neighbour of u then D(v) = c(u,v)

else D(v) = ∞

do {

find w not in N' such that D(w) is a minimum add w to N'

Department of CSE, SBCE Page. 84


CSL 332 Networking Lab SBW20CS025

if(visited[i]==0 && dist[u] +cost[u][i]<dist[i])


{
dist[i]= dist[u] +cost[u][i];
if(last[i]==src)
{
last[i]=u;
}
}
}
}
printf("Routing Table of Node %d\n",src+1);
printf("Destination \tCost\tNext Hop\n");
for(i=0;i<n;i++)
{
if(i==src-1)
{
printf("%d\t\t-\t\t-\n",src+1);
}
else
{
if(last[i]==src)
{
printf("%d\t\t%d\t\t-\n",i+1,dist[i]);
}
else
printf("%d\t\t%d\t\t%d\n",i+1,dist[i],last[i]+1);
}
}
printf("\n");
for(i=0;i<n;i++)
{
if(i!=src)

Department of CSE, SBCE Page. 85


CSL 332 Networking Lab SBW20CS025

update D(v) for each neighbour v of w and not in N'.

D(v) = min{D(v) , D(w) + c(w,v)}

} while ( N' != N)

Department of CSE, SBCE Page. 86


CSL 332 Networking Lab SBW20CS025

{
printf("The cost of the shortest path from router %d to %d is %d\n",src+1,i+1,dist[i]);
}
}
}
int main()
{
int n,j,i,src;
printf("Enter the Number of Nodes:");
scanf("%d",&n);
int cost[n][n];
printf("Enter the cost between Nodes:\n");
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(i!=j)
{
printf("Cost from %d->%d:",i+1,j+1);
scanf("%d",&cost[i][j]); if(cost[i]
[j]==0)
{
cost[i][j]=1000;
}
}
else
{
cost[i][j]=0;
}
}
}

Department of CSE, SBCE Page. 87


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 88


CSL 332 Networking Lab SBW20CS025

printf("Enter the source Node:");


scanf("%d",&src);
printf("Routing Table of Node %d\n",src);
printf("Destination\tCost\tNext Hop\n");
for(i=0;i<n;i++)
{
if(i==src-1)
{
printf("%d\t\t-\t\t-\n",src);
}
else
{
if(cost[src-1][i]==0)
{
printf(" %d\t\t-\t\t-\n",i+1);
}
else
{
printf("%d\t\t%d\t\t-\n",i+1,cost[src-1][i]);
}
}
}
printf("After Applying Dijkstra's Algorithm\n\
n"); shortest_path(n,cost,src-1);
return 0;
}

Department of CSE, SBCE Page. 89


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 90


CSL 332 Networking Lab SBW20CS025

OUTPUT

Department of CSE, SBCE Page. 91


CSL 332 Networking Lab SBW20CS025

RESULT
Program to implement and simulate link state protocol has been executed and output obtained
successfully

Department of CSE, SBCE Page. 92


CSL 332 Networking Lab SBW20CS025

CLIENT PROGRAM

#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
#include<stdlib.h>
#include<ctype.h>
#define MAXLINE 100
int main(int argc,char * argv[])
{
int n;
int sock_fd;
int i=0;
struct sockaddr_in servaddr;
char buf[MAXLINE+1];
char address_buf[MAXLINE],message_buf[MAXLINE];
char * str_ptr,*buf_ptr,*str;
if(argc!=3)
{
fprintf(stderr,"Command is :./client address port\n");
exit(1);
}
if((sock_fd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
printf("Cannot create socket\n");
exit(1);
}
bzero((char*)&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;

Department of CSE, SBCE Page. 93


CSL 332 Networking Lab SBW20CS025

Experiment No : 12
Date :

Implementation Of Simple Mail Transfer Protocol

AIM: To implement a subset of simple mail transfer protocol (SMTP) using UDP

Description:

SMTP provides for mail exchanges between users on the same or different computers. The SMTP
client and server can be divided into two components: user agent (UA) and mail transfer agent
(MTA). The user agent is a program used to send and receive mail. The actual mail transfer is done
through mail transfer agents. To send mail, a system must have client MTA, and to receive mail, a
system must have a server MTA. SMTP uses commands and responses to transfer messages
between an MTA client and MTA server. Commands are sent from the client to the server. It
consists of a keyword followed by zero or more arguments. Examples: HELO, MAIL FROM,
RCPT TO etc. Responses are sent from the server to the client. It is a three-digit code that may be
followed by additional textual information. The process of transferring a mail message occurs in
three phases: connection establishmnet, mail transfer, and connection termination.

Although the transport protocol specified for SMTP is TCP, in this experiment, UDP protocol will
be used.

ALGORITHM:

SMTP Client

1. Create the client UDP socket.

2. Send the message “SMTP REQUEST FROM CLIENT” to the server. This is done so that
the server understands the address of the client.

3. Read the first message from the server using client socket and print it.

Department of CSE, SBCE Page. 94


CSL 332 Networking Lab SBW20CS025

servaddr.sin_port=htons(atoi(argv[2]));
inet_pton(AF_INET,argv[1],&servaddr.sin_addr);
sprintf(buf,"SMTP REQUEST FROM CLIENT\n");
n=sendto(sock_fd,buf,strlen(buf),0,(struct sockaddr*)&servaddr,sizeof(servaddr));
if(n<0)
{
perror("ERROR");
exit(1);
}
if((n=recvfrom(sock_fd,buf,MAXLINE,0,NULL,NULL))==-1)
{
perror("UDP read error");
exit(1);
}
buf[n]='\0';
printf("S:%s",buf);
sprintf(buf,"HELLO name_of_client_mail_server\n");
n=sendto(sock_fd,buf,strlen(buf),0,(struct sockaddr*)&servaddr,sizeof(servaddr));
if((n=recvfrom(sock_fd,buf,MAXLINE,0,NULL,NULL))==-1)
{
perror("UDP read error");
exit(1);
}
buf[n]='\0';
printf("S:%s",buf);
printf("please enter the email address of the
sender:");
fgets(address_buf,sizeof(address_buf),stdin);
address_buf[strlen(address_buf)-1]='\0';
sprintf(buf,"MAIL FROM:<%s>\n",address_buf);
sendto(sock_fd,buf,sizeof(buf),0,(struct sockaddr*)&servaddr,sizeof(servaddr));
if((n=recvfrom(sock_fd,buf,MAXLINE,0,NULL,NULL))==-1)

Department of CSE, SBCE Page. 95


CSL 332 Networking Lab SBW20CS025

4. The first command HELO<”Client's mail server address”> is sent by the client

5. Read the second message from the server and print it.

6. The second command MAIL FROM:<”email address of the sender”> is sent by the client.

7. Read the third message from the server and print it

8. The third command RCPT TO:<”email address of the receiver”> is sent by the client

9. Read the fourth message from the server and print it.

10. The fourth command DATA is sent by the client.

11. Read the fifth message from the server and print it.

12. Write the messages to the server and end with “.”

13. Read the sixth message from the server and print it.

14. The fifth command QUIT is sent by the client.

15. Read the seventh message from the server and print it.

Server

1. Create the server UDP socket

2. Read the message from the client and gets the client's address

3. Send the first command to the client.


220 “server name”

4. Read the first message from the client and print it.

5. Send the second command to the client.


250 Hello “client name”

6. Read the second message from client and print it.

Department of CSE, SBCE Page. 96


CSL 332 Networking Lab SBW20CS025

perror("UDP read error");


exit(1);
}
buf[n]='\0';
printf("S:%s",buf);
printf("please enter the email address of the
receiver:");
fgets(address_buf,sizeof(address_buf),stdin);
address_buf[strlen(address_buf)-1]='\0';
sprintf(buf,"RCPT TO :<%s>\n",address_buf);
sendto(sock_fd,buf,strlen(buf),0,(struct sockaddr*)&servaddr,sizeof(servaddr));
if((n=recvfrom(sock_fd,buf,MAXLINE,0,NULL,NULL))==-1)
{
perror("UDP read error");
exit(1);
}
buf[n]='\0';printf("S:%s",buf);
sprintf(buf,"DATA\n");
sendto(sock_fd,buf,sizeof(buf),0,(struct sockaddr*)&servaddr,sizeof(servaddr));
if((n=recvfrom(sock_fd,buf,MAXLINE,0,NULL,NULL))==-1)
{
perror("UDP read error");
exit(1);
}
buf[n]='\0';
printf("S:%s",buf);
do
{
fgets(message_buf,sizeof(message_buf),stdin);
sprintf(buf,"%s",message_buf);
sendto(sock_fd,buf,strlen(buf),0,(struct sockaddr*)&servaddr,sizeof(servaddr));

Department of CSE, SBCE Page. 97


CSL 332 Networking Lab SBW20CS025

7. Send the third command to the client.


250 “client email address “ Sender
ok

8. Read the third message from client and print it

9. Send the fourth command to the client


250 “server email address” Recepient
ok

10. Read the fourth message from client and print it

11. Send the fifth command to the client


354 Enter mail, end with “.” on a line by itself

12. Read the email text from the client till a “.” is reached

13. Send the sixth command to the client


250 Message accepted for delivery

14. Read the fifth message from the client and print it.

15. Send the seventh command to the client


221 “server name” closing connection

Department of CSE, SBCE Page. 98


CSL 332 Networking Lab SBW20CS025

message_buf[strlen(message_buf)-1]='\0';
str=message_buf;
while(isspace(*str++));
if(strcmp(--str,".")==0)break;
}
while(1);
if((n=recvfrom(sock_fd,buf,MAXLINE,0,NULL,NULL))==-1)
{
perror("UDP read error");
exit(1);
}
buf[n]='\0';sprintf(buf,"QUIT\n"); printf("S:
%s",buf);
sendto(sock_fd,buf,strlen(buf),0,(struct sockaddr*)&servaddr,sizeof(servaddr));
if((n=recvfrom(sock_fd,buf,MAXLINE,0,NULL,NULL))==-1)
{
perror("UDP read error");
exit(1);
}
buf[n]='\0';
printf("S:%s",buf);
}

SERVER PROGRAM
#include<stdio.h>
#include<string.h>
#include<sys/socket.h>
#include<sys/types.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<fcntl.h>
#include<stdlib.h>

Department of CSE, SBCE Page. 99


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 100


CSL 332 Networking Lab SBW20CS025

#include<ctype.h>
#define MAXLINE 100
int main(int argc,char * argv[])
{
int n,sock_fd;
struct sockaddr_in servaddr,cliaddr;char mesg[MAXLINE+1];
socklen_t len;
char *
str_ptr,*buf_ptr,*str;
len=sizeof(cliaddr);
if((sock_fd=socket(AF_INET,SOCK_DGRAM,0))<0)
{
printf("cannot create socket\n");
exit(1);
}
bzero((char*)&servaddr,sizeof(servaddr));
servaddr.sin_family=AF_INET;
servaddr.sin_port=htons(atoi(argv[1]));
servaddr.sin_addr.s_addr=htonl(INADDR_ANY); if(bind(sock_fd,
(struct sockaddr*)&servaddr,sizeof(servaddr))<0)
{
perror("bind failed:");
exit(1);
}
if((n=recvfrom(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,&len))==-1)
{
perror("size not received:");
exit(1);
}
mesg[n]='\0';printf("mesg:%s\n",mesg);
sprintf(mesg,"220 name_of_server_mail_server\n");
sendto(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
n=recvfrom(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,&len);
Department of CSE, SBCE Page. 101
CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 102


CSL 332 Networking Lab SBW20CS025

mesg[n]='\0';
printf("C:%s\n",mesg);
str_ptr=strdup(mesg);
buf_ptr=strsep(&str_ptr," ");
sprintf(mesg,"250 Hello %s",str_ptr);
free(buf_ptr);
sendto(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
n=recvfrom(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,&len);
mesg[n]='\0';
printf("C:%s",mesg);
str_ptr=strdup(mesg);
buf_ptr=strsep(&str_ptr,":");
str_ptr[strlen(str_ptr)-1]='\0';
sprintf(mesg,"250 Hello %s. sender ok\n",str_ptr);
free(buf_ptr);
sendto(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
n=recvfrom(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,&len);
mesg[n]='\0';
printf("C:%s",mesg);
str_ptr=strdup(mesg);
buf_ptr=strsep(&str_ptr,":");
str_ptr[strlen(str_ptr)-1]='\0';
sprintf(mesg,"250 Hello %s, Recepient ok\n",str_ptr);
free(buf_ptr);
sendto(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
n=recvfrom(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,&len);
mesg[n]='\0';
printf("C:%s",mesg);
sprintf(mesg,"354 Enter mail,end with \".\" on a line by itself\n");
sendto(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
while(1)

Department of CSE, SBCE Page. 103


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 104


CSL 332 Networking Lab SBW20CS025

{
n=recvfrom(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,&len);
mesg[n]='\0';
printf("C:%s",mesg);
mesg[strlen(mesg)-1]='\0';
str=mesg;
while(isspace(*str++));
if(strcmp(--str,".")==0)break;
sprintf(mesg,"250 messages accepted for delivery \n");
sendto(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,sizeof(cliaddr));
n=recvfrom(sock_fd,mesg,MAXLINE,0,(struct sockaddr*)&cliaddr,&len);
mesg[n]='\0';
printf("C:%s\n",mesg);
sprintf(mesg,"221 serves mail server closing connection\n"); sendto(sock_fd,mesg,MAXLINE,0,
(struct sockaddr*)&cliaddr,sizeof(cliaddr));
}
}

OUTPUT

Department of CSE, SBCE Page. 105


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 106


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 107


CSL 332 Networking Lab SBW20CS025

RESULT
Program to implement a subset of simple mail transfer protocol (SMTP) using UDP has been
executed and output obtained successfully

Department of CSE, SBCE Page. 108


CSL 332 Networking Lab SBW20CS025

PROGRAM
#include<stdio.h>
int main()

{
int incoming,outgoing,buck_size,n,store=0;
printf("Enter bucket size,outgoing rate and no of
inputs:"); scanf("%d%d%d",&buck_size,&outgoing,&n);
while(n!=0)
{
printf("Enter the incoming packet size:");
scanf("%d",&incoming);
printf("incoming packet size %d\
n",incoming); if(incoming<=(buck_size-store))
{
store+=incoming;
printf("Bucket buffer size %d out of %d\n",store,buck_size);
}
else
{
printf("Dropped %d no of packet\n",incoming-(buck_size-store));
printf("Bucket buffer size %d out of %d\n",store,buck_size);
store=buck_size;
}
store=store-outgoing;
printf("After outgoing %d packets left out of %d in buffer \
n",store,buck_size); n--;
}
}

Department of CSE, SBCE Page. 109


CSL 332 Networking Lab SBW20CS025

Experiment No : 13
Date :

Congestion control algorithm using Leaky Bucket Algorithm

AIM: : Write a program for congestion control using Leaky bucket algorithm.

Theory

The congesting control algorithms are basically divided into two groups: open loop and closed loop.
Open loop solutions attempt to solve the problem by good design, in essence, to make sure it does
not occur in the first place. Once the system is up and running, midcourse corrections are not made.
Open loop algorithms are further divided into ones that act at source versus ones that act at the
destination. In contrast, closed loop solutions are based on the concept of a feedback loop if there is
any congestion. Closed loop algorithms are also divided into two sub categories: explicit feedback
and implicit feedback. In explicit feedback algorithms, packets are sent back from the point of
congestion to warn the source. In implicit algorithm, the source deduces the existence of congestion
by making local observation, such as the time needed for acknowledgment to come back. The
presence of congestion means that the load is (temporarily) greater than the resources (in part of the
system) can handle. For subnets that use virtual circuits internally, these methods can be used at the
network layer. Another open loop method to help manage congestion is forcing the packet to be
transmitted at a more predictable rate. This approach to congestion management is widely used in
ATM networks and is called traffic shaping. The other method is the leaky bucket algorithm.

Each host is connected to the network by an interface containing a leaky bucket, that is, a finite
internal queue. If a packet arrives at the queue when it is full, the packet is discarded. In other
words, if one or more process are already queued, the new packet is unceremoniously discarded.
This arrangement can be built into the hardware interface or simulate d by the host operating
system. In fact it is nothing other than a single server queuing system with constant service time.

The host is allowed to put one packet per clock tick onto the network. This mechanism turns an
uneven flow of packet from the user process inside the host into an even flow of packet onto the
network, smoothing out bursts and greatly reducing the chances of congestion.

Department of CSE, SBCE Page. 110


CSL 332 Networking Lab SBW20CS025

OUTPUT

Department of CSE, SBCE Page. 111


CSL 332 Networking Lab SBW20CS025

ALGORITHM

1. Start
2. Set the bucket size or the buffer size.
3. Set the output rate.
4. Transmit the packets such that there is no overflow.
5. Repeat the process of transmission until all packets are transmitted. (Reject packets where its
size is greater than the bucket size)
6. Stop

RESULT
Program to implement congestion control using Leaky bucket algorithm has been executed and
output obtained successfully.

Department of CSE, SBCE Page. 112


CSL 332 Networking Lab SBW20CS025

Department of CSE, SBCE Page. 113

You might also like