Network Lab605
Network Lab605
PATHANAMTHITTA – 689625
LABORATORY RECORD
of Sixth Semester Computer science and Engineering branch in the CSL 332
Faculty in Charge
Experiment No : 1
Date :
AIM: Familiarize and understand the basics of network configuration files and networking
commands in Linux
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.
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.
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
4. /etc/nsswitch.conf
This file includes database search entries. The directive specifies which database is to be searched
first.
1. ifconfig
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.
2. netstat
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
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
RESULT
Familiarized and understood the basics of network configuration files and networking commands in
Linux
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.
This command tells which all processes are running on the system when ps runs.
ps -ef
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
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
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));
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>
RESULT
Familiarized and understood the use and functioning of system calls used for network
programming in Linux.
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>
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);
Experiment No : 3
Date :
Description:
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.
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;
};
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);
}
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);
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 binary value of the dotted decimal IP address is stored in the field when the function returns.
This is optional in the case of client and we usually do not use the bind function on the client side.
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.
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>
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)
{
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.
6. Writing to a socket
In the case of TCP connection writing to a socket can be done using the write system call
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.
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
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);
}
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.
The listen function is used on the server in the connection oriented communication to prepare a
socket to accept messages from clients.
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.
The accept function is used on the server in the case of connection oriented communication to
accept a connection request from a client.
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.
OUTPUT
ALGORITHM
Client
1. Create socket
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
Server
6. Read the string using the connection socket from the client
RESULT
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;
}
Experiment No : 4
Date :
AIM: Client sends a message to the server using udp protocol. The server displays the message,
when it receives it to the client .
Description:
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.
struct sockaddr_in {
u_short sin_family; u_short sin_port;
struct in_addr sin_addr;
char sin_zero[8]; /*unused, always zero*/
};
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;
}
struct in_addr {
u_long s_addr;
sin_addr is used to store the IP address of the server machine and is of type struct in_addr
The binary value of the dotted decimal IP address is stored in the field when the function returns.
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.
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
OUTPUT
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
ALGORITHM
Client
1. Create socket
2. Read the message from the standard input and send it to server using socket
Server
1. Create socket
RESULT
Program to implement client-server communication using socket programming and UDP as
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;
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.
SERVER PROGRAM
#include<stdio.h>
#include<sys/socket.h>
#include<string.h>
#include<arpa/inet.h>
#include<unistd.h>
int main()
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)
OUTPUT
RESULT
Program to implement a chat server so that multiple users can chat simultaneously has been
executed and output obtained successfully
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>
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
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>
#include<unistd.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<time.h>
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(;;)
{
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
RESULT
Program to implement a concurrent time server using UDP has been executed and output obtained
successfully
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);
Experiment No : 7
Date :
Stop And Wait
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;
}
}
Server
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;
OUTPUT
RESULT
Program to to simulate stop – and – wait protocol has been executed and output obtained
successfully
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;
}
}
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.
• 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
printf("\n");
i+=x;
}
printf("Total number of tramissions :%d\n",tr);
return 0;
}
OUTPUT
RESULT
Program to perform simulation on sliding window protocol using Go-back-N ARQ has
been executed and output obtained successfully
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";
Experiment No : 9
Date :
Selective Repeat
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.
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
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>
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;
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);
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:
end while
end if
end if
end while
end
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;
}
OUTPUT
RESULT
Program to simulate selective repeat protocol has been executed and output obtained successfully
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++)
Experiment No : 10
Date :
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:
-Associated with each link connected to a router, there is a link cost (static or dynamic).
-Intermediate hops
Distance to itself = 0
Distance to ALL other routers = infinity number or a finite cost (distance) value based on hop count.
-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.
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
It receives a distance vector from a neighbour containing different information than before.
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
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++)
{
Experiment No : 11
Date :
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}
else D(v) = ∞
do {
} while ( N' != N)
{
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;
}
}
}
OUTPUT
RESULT
Program to implement and simulate link state protocol has been executed and output obtained
successfully
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;
Experiment No : 12
Date :
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
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.
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)
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.
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.
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.
15. Read the seventh message from the server and print it.
Server
2. Read the message from the client and gets the client's address
4. Read the first message from the client and print it.
12. Read the email text from the client till a “.” is reached
14. Read the fifth message from the client and print it.
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>
#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
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)
{
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
RESULT
Program to implement a subset of simple mail transfer protocol (SMTP) using UDP has been
executed and output obtained successfully
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--;
}
}
Experiment No : 13
Date :
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.
OUTPUT
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.