Network-OS Lab Manual LINUX - THE OS Linux is a Unix-like computer operating system. Linux is one of the most prominent examples of free software and open source development; its underlying source code can be modified, used, and redistributed by anyone, freely. The Linux kernel was first released to the public on 17 September 1991, for the Intel x86 PC architecture. The kernel was augmented with system utilities and libraries from the GNU project to create a usable operating system, which later led to the alternate term GNU/Linux.Linux is now packaged for different uses in Linux distributions, which contain the kernel along with a variety of other software packages tailored to requirements. Predominantly known for its use in servers, Linux has gained the support of corporations such as IBM, Sun Microsystems, Hewlett-Packard, and Novell, and is used as an operating system for a wide variety of computer hardware, including desktop computers, supercomputers, and embedded devices such as mobile phones and routers. The Unix operating system was conceived and implemented in the 1960s and first released in 1970. Its wide availability and portability meant that it was widely adopted, copied and Department Of Computer Science BM II College Of Engineering, Sasthamcotta 1
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Network-OS Lab Manual
LINUX - THE OS
Linux is a Unix-like computer operating system. Linux is one of the most prominent
examples of free software and open source development; its underlying source code can be
modified, used, and redistributed by anyone, freely.
The Linux kernel was first released to the public on 17 September 1991, for the Intel
x86 PC architecture. The kernel was augmented with system utilities and libraries from the
GNU project to create a usable operating system, which later led to the alternate term
GNU/Linux.Linux is now packaged for different uses in Linux distributions, which contain
the kernel along with a variety of other software packages tailored to requirements.
Predominantly known for its use in servers, Linux has gained the support of
corporations such as IBM, Sun Microsystems, Hewlett-Packard, and Novell, and is used as
an operating system for a wide variety of computer hardware, including desktop computers,
supercomputers, and embedded devices such as mobile phones and routers.
The Unix operating system was conceived and implemented in the 1960s and first
released in 1970. Its wide availability and portability meant that it was widely adopted,
copied and modified by academic institutions and businesses, with its design being
influential on authors of other systems.
A 2001 study of Red Hat Linux 7.1 found that this distribution contained 30 million
source lines of code. Using the Constructive Cost Model, the study estimated that this
distribution required about eight thousand man-years of development time. According to the
study, if all this software had been developed by conventional proprietary means, it would
have cost about 1.08 billion dollars (year 2000 U.S. dollars) to develop in the United States.
Most of the code (71%) was written in the C programming language, but many other
languages were used, including C++, Lisp, assembly language, Perl, Fortran, Python and
Department Of Computer Science BM II College Of Engineering, Sasthamcotta1
//to wait for the thread to finish execution. while(end<2) { }
Department Of Computer Science BM II College Of Engineering, Sasthamcotta12
Network-OS Lab Manual
}
//function prototype for the thread function.void * add(void * args){ int a,b; printf("\nEntered into %d thread\n",args); printf("\nEnter the first number for thread %d\n",args); scanf("%d",&a);
printf("\nEnter the second number for thread %d\n",args); scanf("%d",&b);
printf("The sum computed by thread %d:\t%d\n",args,a+b); end++;}
Output
DYNAMIC MULTITHREAD CREATION
Department Of Computer Science BM II College Of Engineering, Sasthamcotta13
Network-OS Lab Manual
Algorithm
1. Start.
2. Provide the function prototype and definition for the function that
has to be used as thread.
3. Declare variables to store the thread id and thread attributes.
4. Accept the no. of threads from the user.
5. Create the threads by suitably initialising the thread variables.
6. Wait until the threads execute.
7. Stop.
Program
/*Program to describe dynamic multiple thread creation and passing arguments to it.
* This program illustrates the steps involved in creating multiple threads dynamically.
* This program accepts the number of threads from the user and creates it at run time.
* The procedure is similar to that we used to create multiple threads.
NOTE:->This module can be compiled using the command 'cc dynamic multithread creation.c -lpthread' and executed using './a.out'
//for accepting the number of threads to be created. printf("\nEnter the number of threads.\n"); scanf("%d",&count); for(i=0,j=count;i<count;i++,j--) {
//inserting the arguments for the thread args[0]=i+1; args[1]=j;
//function prototype for the thread function.void * display_function();
//global semaphore variable to be shared.sem_t sem_var;
int main(){ pthread_t tid; pthread_attr_t attr; int i;//initialising the semaphore variable with an initial value 0 (third arguement.) sem_init(&sem_var,0,0);
printf("\n\t****** The value of DATA is:\t%d ******\n",data);}
//definition of first thread function.void * thread_function1(){ int a;
printf("\nEntered into thread function:1\n");
Department Of Computer Science BM II College Of Engineering, Sasthamcotta23
Network-OS Lab Manual
printf("\nThread function:1 waiting to gain access\n");
sleep(1); sem_wait(&sem_var); printf("\nAccess gained by thread function:1\n");
printf("\nThread function:1 using the value of 'DATA' \n");
a=data; a=a+1; data=a;
sem_post(&sem_var); printf("\nResources released by thread function:1\n"); end++;}
//definition of second thread function.void * thread_function2(){ int b;
printf("\nEntered into thread function:2\n"); printf("\nThread function:2 waiting to gain access\n");
sleep(1); sem_wait(&sem_var); printf("\nAccess gained by thread function:2\n"); printf("\nThread function:2 using the value of 'DATA' \n"); b=data; b=b+1; data=b;
sem_post(&sem_var); printf("\nResources released by thread function:2\n"); end++;}
Output
Department Of Computer Science BM II College Of Engineering, Sasthamcotta24
Network-OS Lab Manual
DINING PHILOSOPHER’S PROBLEM
Department Of Computer Science BM II College Of Engineering, Sasthamcotta25
Network-OS Lab Manual
The problem
The dining philosophers problem is summarized as five philosophers sitting at a table
doing one of two things - eating or thinking. While eating, they are not thinking, and while
thinking, they are not eating. The five philosophers sit at a circular table with a large bowl of
spaghetti in the center. A fork is placed in between each philosopher, and as such, each
philosopher has one fork to his or her left and one fork to his or her right. As spaghetti is
difficult to serve and eat with a single fork, it must be assumed that in order for a philosopher
to eat, the philosopher must have two forks. In the case of the dining philosopher, the
philosopher can only use the fork on his or her left or right.
Illustration of the dining philosophers problem
In some cases, the dining philosophers problem is explained using rice and chopsticks
as opposed to spaghetti and forks, as it is generally easier to understand that two chopsticks
are required, whereas one could arguably eat spaghetti using a single fork, or using a fork and
a spoon. In either case, only one instrument (fork or chopstick) can be picked up at a time,
and the philosopher must have two instruments in order to eat.
Department Of Computer Science BM II College Of Engineering, Sasthamcotta26
printf("\n\n\t\tNO. OF PHILOSOPHERS :5");printf("\n\n\t\tNO. OF FORKS(SPOONS):5\n\n"); printf("_____________________________________________________________________________________");
Department Of Computer Science BM II College Of Engineering, Sasthamcotta29
Network-OS Lab Manual
printf("\n\n\n\t\tPRESS ENTER TO CONTINUE....................."); fgets(a,2,stdin);
while(i<6) { cls(); printf("\n\t\t\tWaiting for the request.............\n");
delay(); printf("\n\tRequest obtained from the process P%d ",req_queue[i]+1); if(req_type[i]==0) { printf("for resource allocation.\n"); printf("\nGetting request.....\n");
getrequest(req_queue[i]);
Department Of Computer Science BM II College Of Engineering, Sasthamcotta42
Network-OS Lab Manual
printf("\nChecking safe state.....\n"); delay(); if(issafe()) { printf("\nSafe state detected....\nAllocating resources .......\n"); allocate(req_queue[i]); } else { printf("\nUnsafe state detected....\nInserting the process into waiting queue.\n"); j=j+1; wait_queue[j]=req_queue[i]; } }
else { printf("for resource deallocation.\n"); deallocate(req_queue[i]); printf("\nDeallocation done.\n\n%d processes in the wait queue\n",j); if(j>0) { while(j>0) { printf("\nConsidering the waiting queue process P%d\n",wait_queue[j]+1); getrequest(wait_queue[j]); printf("\nChecking safe state.\n"); delay(); if(issafe()) { printf("\nSafe state detected\nResources allocated\n"); allocate(wait_queue[j]); j--; } else { break; } } } } delay(); i++; }}
Department Of Computer Science BM II College Of Engineering, Sasthamcotta43
Network-OS Lab Manual
void getrequest(int i){ int j; for(j=0;j<4;j++) { request[j]=max_req_res[i][j]-cur_allocated_res[i][j]; }}
int issafe(){ int j; for(j=0;j<4;j++) { if(request[j]>available_res[j]) { return 0; } } return 1;}
//retriving the total no. of blocks. totalblocks=buf.f_blocks;
//retriving the blocksize. blocksize=buf.f_bsize;
//retriving the free disk space.
Department Of Computer Science BM II College Of Engineering, Sasthamcotta50
Network-OS Lab Manual
freeblocks=buf.f_bfree;
printf("\n\tThe total disk size:\t%lu (bytes)\n",totalblocks*blocksize); printf("\n\tThe free disk space:\t%lu (bytes)\n",freeblocks*blocksize); printf("\n\tThe used disk space:\t%lu (bytes)\n",(totalblocks*blocksize)-(freeblocks*blocksize)); } else { printf("\nERROR:Cannot open the file specified.\n"); }}
Output
64 ./nw
336 .
FileSystem Size Used Avail Use % Mounted On
/dev/mapper/VolGroup00-Log Vo100
35G 3.2G 30G 10% /
/dev/hda1 99M 12M 82M 13% /boot
None 498M 0 498M 0% /dev/shm
Department Of Computer Science BM II College Of Engineering, Sasthamcotta51
Network-OS Lab Manual
PIPES
Theory
A pipe is a method of connecting the standard output of one process to the standard
input of another. Pipes are the eldest of the IPC tools, having been around since the earliest
incarnations of the UNIX operating system. They provide a method of one-way
communications (hence the term half-duplex) between processes.
This feature is widely used, even on the UNIX command line (in the shell).
When a process creates a pipe, the kernel sets up two file descriptors for use by the
pipe. One descriptor is used to allow a path of input into the pipe (write), while the other is
used to obtain data from the pipe (read). At this point, the pipe is of little practical use, as the
creating process can only use the pipe to communicate with itself.
While a pipe initially connects a process to itself, data traveling through the pipe
moves through the kernel. Under Linux, in particular, pipes are actually represented
internally with a valid inode. Of course, this inode resides within the kernel itself, and not
within the bounds of any physical file system. This particular point will open up some pretty
handy I/O doors for us, as we will see a bit later on.
At this point, the creating process typically forks a child process. Since a child
process will inherit any open file descriptors from the parent, we now have the basis for
multiprocess communication (between parent and child). It is at this stage, that a critical
decision must be made. In which direction do we desire data to travel? Does the child process
send information to the parent, or vice-versa? The two processes mutually agree on this issue,
and proceed to ``close'' the end of the pipe that they are not concerned with.
To access a pipe directly, the same system calls that are used for low-level file I/O
can be used (recall that pipes are actually represented internally as a valid inode).
Department Of Computer Science BM II College Of Engineering, Sasthamcotta52
Network-OS Lab Manual
To send data to the pipe, we use the write() system call, and to retrieve data from the
pipe, we use the read() system call. Remember, low-level file I/O system calls work with file
descriptors! However, keep in mind that certain system calls, such as lseek(), do not work
with descriptors to pipes.
To create a simple pipe with C, we make use of the pipe() system call. It takes a
single argument, which is an array of two integers, and if successful, the array will contain
two new file descriptors to be used for the pipeline.
SYSTEM CALL: pipe();
PROTOTYPE: int pipe( int fd[2] );
RETURNS: 0 on success
-1 on error: errno = EMFILE (no free descriptors)
EMFILE (system file table is full)
EFAULT (fd array is not valid)
NOTES: fd[0] is set up for reading, fd[1] is set up for writing
The popen() function creates a pipe between the calling program and the
command to be executed. The arguments topopen() are pointers to null-terminated strings.
The com-mand argument consists of a shell command line. The modeargument is an I/O
mode, either r for reading or w for writing. The value returned is a stream pointer such that
one can write to the standard input of the command, if the I/Omode is w, by writing to the
file stream and one can read from the standard output of the command, if the I/O mode is r,
by reading from the file stream.
The pclose() function closes a stream opened by popen() by closing the pipe. It
waits for the associated process to terminate and returns the termination status of the process
running the command language interpreter. This is the value returned by waitpid(2).
Department Of Computer Science BM II College Of Engineering, Sasthamcotta53
... key_t key; /* key to be passed to shmget() */ int shmflg; /* shmflg to be passed to shmget() */ int shmid; /* return value from shmget() */ int size; /* size to be passed to shmget() */
shmctl() is used to alter the permissions and other characteristics of a shared memory segment. It is prototyped as follows:
int shmctl(int shmid, int cmd, struct shmid_ds *buf);
The process must have an effective shmid of owner, creator or superuser to perform this command. The cmd argument is one of following control commands:
SHM_LOCK -- Lock the specified shared memory segment in memory. The process must have the effective ID of superuser to perform this command.
SHM_UNLOCK -- Unlock the shared memory segment. The process must have the effective ID of superuser to perform this command.
IPC_STAT -- Return the status information contained in the control structure and place it in the buffer pointed to by buf. The process must have read permission on the segment to perform this command.
IPC_SET
Department Of Computer Science BM II College Of Engineering, Sasthamcotta60
Network-OS Lab Manual
-- Set the effective user and group identification and access permissions. The process must have an effective ID of owner, creator or superuser to perform this command.
IPC_RMID -- Remove the shared memory segment.
The buf is a sructure of type struct shmid_ds which is defined in <sys/shm.h>
Program
Server
/*Program to demonstrate the use of shared memory in interprocess communication.
* This program acts as a server which waits for a message from the client process.
* The process is implemented using a shared memory space called 'shared_location'.
* The 'message' part of this space stores the message while the 'written' part is used to
indicate whether the server has read the message or the client has written the
message.(0->read,1->written).
* This module should be compiled and executed first.
* This module is compile using 'cc shmserver.c' and executed using './a.out'*/
//structure definition for acquiring a shared location.struct shared_location{ int written; char message[30];};
int main(){ int shmid,running;
Department Of Computer Science BM II College Of Engineering, Sasthamcotta61
Network-OS Lab Manual
void *address; struct shared_location * ptr;
//for getting a shared location shmid=shmget((key_t)1234,sizeof(struct shared_location),0666|IPC_CREAT);
//optional if required for error checking. if(shmid<=0) { printf("\nERROR:\tCannot allocate shared space.\n"); exit(0); }
//attaching the shared location to this process. address=shmat(shmid,(void *)0,0);
//optional if required for error checking. if(address==(void*)0) { printf("\nEROOR:\tShared location cannot be attached.\n"); }
//type casting so as to convert the obyained location into our format. ptr=(struct shared_location*)address;
ptr->written=0; strcpy(ptr->message,"Hi I am server."); running=1;
while(running) { printf("\nWaiting for the client to enter the message.\n"); while(ptr->written==0) { } if(ptr->written==1) { printf("The client has entered the message: %s\n",ptr->message); } ptr->written=0; if(strcmp(ptr->message,"end")==0) { running=0; } }
//detaching the shared location. shmdt(address);
Department Of Computer Science BM II College Of Engineering, Sasthamcotta62
Network-OS Lab Manual
//deleting the shared location. shmctl(shmid,IPC_RMID,NULL);}
Output
Client
Program
/* Program to demonstrate the use of shared memory in interprocess communication.
* This module acts as a client which sends messages to the server process.
* In this the message entered into the message part of the 'shared_location' structure and
the 'written' field is set to 1.
* The remaining process is similar to that of the server process.
* This module can be compiled using 'cc shmclient.c -o b' and executed using './b'
//inculsion
Department Of Computer Science BM II College Of Engineering, Sasthamcotta63
//structure definition for the shared location.struct shared_location{ int written; char message[30];};//the functions and other terms used have similar meanings to that used in the server module //but they don't bear any specific relationship.
int main(){ int shmid,running; void *address; struct shared_location * ptr;
#include<stdio.h>main(){printf("\nThe Directory Listing\n");execl("/bin/ls","ls","-l",NULL);printf("This Line will not be printed");}
2.Program to fork a child process and display details of parent & child processes
#include<sys/types.h>main(){int pid;pid=fork();if(pid==0){printf("I am child,My id is %d\n & my parents id is %d\n\n",getpid(),getppid());}else{printf("I am parent,My id is %d\n\n",getpid());printf("My child is %d\n\nMy Parent is %d",pid,getppid());}}
Department Of Computer Science BM II College Of Engineering, Sasthamcotta66
Network-OS Lab Manual
3.Program to call a new process using EXEC function from a child process
printf("I am child,My id is %d\n & my parents id is %d\n\n",getpid(),getppid());execl("f2",0);printf("Child Terminated");}else{printf("I am parent,My id is %d\n\n",getpid());printf("My child is %d\n\nMy Parent is %d",pid,getppid());}}
// Create another simple program. Compile it to f2( redirect output to f2). f2 will be executed by the above written program.
3. Program to demonstrate interprocess communication between a parent process and a child process.
//This is to and fro communication through a single pipe.
Department Of Computer Science BM II College Of Engineering, Sasthamcotta67
Network-OS Lab Manual
printf("Enter the data for the parent");fgets(buf,sizeof(buf),stdin);write(fd[1],buf,sizeof(buf));sleep(20);read(fd[0],buf,sizeof(buf));printf("Got From Parent");puts(buf);
}else{
sleep(10);printf("In Child %d %d ",pid,getppid());read(fd[0],buf,sizeof(buf));printf("From Child");puts(buf);printf("I am Parent");printf("Enter message for Child");fgets(buf,sizeof(buf),stdin);write(fd[1],buf,sizeof(buf));
}}
5.Suppose we are given a number N which is quite large. We need to find all its factors. We decide to have some computation in parallel so we divide the N by the range of numbers from 2 to √N/2 and √N/2 +1. We fork two child processes to work over each of these ranges. Write a program to implement the above scheme using fork(). The parent should output only distinct factors.
Department Of Computer Science BM II College Of Engineering, Sasthamcotta69
Network-OS Lab Manual
//printf("parent");printf("\n%d >>>child2",i);}
}
}
6. Write a program to detect deadlock when a number of processes are running. The number of available resources, number of resources allocated to processes are accepted..
#include<stdio.h>
void read_alloc(int A[10][10],int m , int n ){
int i ,j ;for(i=0;i<n;i++){printf("for process %d the no: of allocated resources of .....\n",i);for(j=0;j<m;j++){printf("type%d:",j);
scanf ("%d",&A[i][j]);}}
}void read_reqst(int RQ[10][10],int m,int n){
int i ,j ;for (i=0;i<n;i++){printf("for process %d the no: of required resources of .....\n",i);
for(j=0;j<m;j++){printf("type%d:",j);
scanf ("%d",&RQ[i][j]);}}
}void read_avail(int A[10],int m ){ int i ;
printf("Enter the available resources of ........\n");
Department Of Computer Science BM II College Of Engineering, Sasthamcotta70
Network-OS Lab Manual
for (i=0;i<m ;i++){printf("Type %d ",i);scanf("%d",&A[i]);}
}void calc_deadlock(int A[10][10],int RQ[10][10],int AVAIL[10],int m,int n ){
int w[10],f[10],i,j,fg=0;for(i=0;i<m;i++)w[i]=AVAIL[i];for(i=0;i<n;i++){
Department Of Computer Science BM II College Of Engineering, Sasthamcotta71
Network-OS Lab Manual
fg=0;for(i=0;i<n;i++){
if (f[i]==0){
printf(" the system is in deadlock by the process %d ....",i);getchar();fg=1;break;}}
if (fg==0){printf(" there is no deadlock");getchar();}
}
int main(){int m , n , A[10][10],AVAIL[10],RQ[10][10];system("clear");printf("enter the total number of processes running:");scanf("%d",&n);printf (" enter the total no: of resource types :");scanf ("%d",&m);read_alloc(A,m,n);system("clear");read_reqst(RQ,m,n);system("clear");read_avail(AVAIL,m);calc_deadlock(A,RQ,AVAIL,m,n);getchar();}
7.Write a program to send and receive messages through message queue
Department Of Computer Science BM II College Of Engineering, Sasthamcotta73
Network-OS Lab Manual
long mtype;char data[30];
}message;
int main(){
message send,rec;student s;int i;key_t key=3151;sleep(20);printf("In Process 2");
int msgid=msgget(key,IPC_CREAT|0666);if(msgid==-1){
fprintf(stderr,"Error Creating Or Opening mq\n");return EXIT_FAILURE;
}sleep(20);int j=0;do{
j++;if(msgrcv(msgid,(void *)&rec,30,1,0)==-1){
fprintf(stderr,"Error Writting To mq\n");break;
}fprintf(stdout,"Receiver Got %s\n",rec.data);
}while(strncmp(send.data,"quit",4)!=0);
}
8.Suppose we have 4 matrices A , B, C and D , each of size N X N , we need to compute the matrix product A X B, A X C , A X D . Write a pgm to compute the desired result using shared memory mechanism.
Department Of Computer Science BM II College Of Engineering, Sasthamcotta76
Network-OS Lab Manual
system("clear");printf("enter the rows and columnsof matrix B....\n");scanf("%d %d",&r2,&c2);shared_mem[2]=r2;shared_mem[3]=c2;printf("enter the elementsof matrix B....\n");read_matrix(address,B,r2,c2,shared_mem);address=address+(r2*c2);
//FOR MATRIX Csystem("clear");printf("enter the rows and columnsof matrix C....\n");scanf("%d %d",&r3,&c3);shared_mem[4]=r3;shared_mem[5]=c3;printf("enter the elementsof matrix C....\n");read_matrix(address,C,r3,c3,shared_mem);address=address+(r3*c3);
//FOR MATRIX D system("clear");printf("enter the rows and columnsof matrix D.....\n");scanf("%d %d",&r3,&c3);shared_mem[6]=r3;shared_mem[7]=c3;printf("enter the elementsof matrix D...\n");read_matrix(address,C,r3,c3,shared_mem);address=address+(r3*c3);
//FORK A CHILDchild=fork();if(child ==0){
sleep(10);//INVOKE ANOTHER PROGRAM SHM2(EXE),PASS ARGUMENT- STR
execlp("./shm2","shm2",str,NULL);}multiply(A,B,r1,c1,r2,c2);shmdt(shared_mem);//DETACH SHARED MEMORYprintf("closing process 1...............\n");
}
//Process1 reads matrices from keyboard and stores to shared memory. AXB is simple computation without using shared memory. Write another program (shm2.c) The Shared
Department Of Computer Science BM II College Of Engineering, Sasthamcotta77
Network-OS Lab Manual
memory id is passed to this program through exec function. Exec takes only string arguments. So id value is converted to string.Shm2.c is compiled to shm2 and is called from process1.You have to run only process1. Locations 0 to 7 of shared memory contain number of rows and columns of 4 matrices. Actual matrix elements are stored from location 8 onwards.………………………………………………………………………………………………………………………………………………………………………………………….
//READ MATRIX Cr3=shared_mem[4];c3=shared_mem[5];read_from_shm(C,shared_mem,add,r3,c3);add=add+(r3*c3);printf("\n The Result of A X C from process 2.......\n");
multiply(A,C,r1,c1,r3,c3);
Department Of Computer Science BM II College Of Engineering, Sasthamcotta79
Network-OS Lab Manual
//READ MATRIX Dr3=shared_mem[6];c3=shared_mem[7];read_from_shm(D,shared_mem,add,r3,c3);sleep(3);printf("\n.. The Result of A X D from process 2..............\n");multiply(A,D,r1,c1,r3,c3);
int bytes=0, i; char w_buffer[BUF_SIZE], r_buffer[BUF_SIZE]; do { //Read the string from the pipe. memset(r_buffer, '\0', sizeof(r_buffer)); read(r_pipe, r_buffer, sizeof(r_buffer)); fprintf(stdout, "I got %s\n", r_buffer); //Process the string; strcpy(w_buffer, r_buffer); for(i=0;i<strlen(w_buffer);++i) w_buffer[i] = w_buffer[i]+1;
//Write the string back into the pipe. bytes = write(w_pipe, w_buffer, strlen(w_buffer)); if( bytes==-1 ) fprintf(stderr, "Write error in FIFO!\n"); }while( strncmp(r_buffer, "quit", 4)!=0 );
close(w_pipe);
Department Of Computer Science BM II College Of Engineering, Sasthamcotta81
Network-OS Lab Manual
close(r_pipe);
fprintf(stdout, "WORKING Process finished [PID=%d]\n", (int)getpid() );
int bytes; char w_buffer[BUF_SIZE], r_buffer[BUF_SIZE];
do{ fprintf(stdout, "Enter something to be sent for PROCESSING :"); fgets(w_buffer, BUF_SIZE-1, stdin); w_buffer[strlen(w_buffer)-1] = '\0';
//Write the string into the pipe. bytes = write(w_pipe, w_buffer, strlen(w_buffer)); if( bytes<0 ) fprintf(stderr, "Error writing to pipe! Data lost??"); //Read string from pipe, after processing. memset(r_buffer, '\0', sizeof(r_buffer)); read(r_pipe, r_buffer, sizeof(r_buffer)); fprintf(stdout, "The string after processing is :%s\n", r_buffer); }while( strncmp(w_buffer, "quit", 4)!=0 );
close(w_pipe); close(r_pipe);
fprintf(stdout, "IO Handler Process finished [PID=%d]\n", (int)getpid() ); return 0;}
//Producer program produces items and writes to a FIFO. Consumer reads this FIFO and processes the items. The processed items are written to another FIFO. This is read by the producer.
GENERAL INSTRUCTIONS
For programs that are sender-receiver or client-server type(ftp, mac, smtp, ipc using sockets, messageQ, named pipes)g++ <sender.c> -o senderg++ <receiver.c> -o recv
then run in 2 terminals(always server/receiver first) as:./recv <port>./sender <IP> <port>
if its not a NW pgm(eg: msgQs, named pipes) just run as:
Department Of Computer Science BM II College Of Engineering, Sasthamcotta83
Network-OS Lab Manual
./recv
./sender
compiling RPC:
there are 3 files initially, which we code... finger.x, client.c, server.c
//variables to store the socket id. int serversocket,clientsocket;
//variables to store the network host addresses. sockaddr_in serveraddr,clientaddr;
//variable to store address length. socklen_t len; char message[50];
//creating a socket. serversocket=socket(AF_INET,SOCK_STREAM,0);
//steps to include the host address bzero((char*)&serveraddr,sizeof(serveraddr)); serveraddr.sin_family=AF_INET; serveraddr.sin_port=htons(5030); serveraddr.sin_addr.s_addr=INADDR_ANY;
//binding the socket to the operating system. bind(serversocket,(sockaddr*)&serveraddr,sizeof(serveraddr));
//variable to store the socket_id. int clientsocket;
//variable to store the address. sockaddr_in serveraddr;
//variableto store the address length. socklen_t len;
//variable to store the network byte order address. hostent *server; char message[50];
//socket creation.
Department Of Computer Science BM II College Of Engineering, Sasthamcotta93
Network-OS Lab Manual
clientsocket=socket(AF_INET,SOCK_DGRAM,0);//steps involved in the server address creation.
bzero((char*)&serveraddr,sizeof(serveraddr)); len=sizeof(serveraddr); serveraddr.sin_family=AF_INET; serveraddr.sin_port=htons(5015); server=gethostbyname("127.0.0.1"); bcopy((char*)server->h_addr,(char*)&serveraddr.sin_addr.s_addr,sizeof(server->h_addr)); printf("\nPRESS ENTER TO START THE CONNECTION PROCESS.\n"); fgets(message,2,stdin);
printf("\nSending message for server connection\n");//sending message.
sendto(clientsocket,"HI I AM CLIENT...",sizeof("HI I AM CLIENT...."),0,(sockaddr*)&serveraddr,sizeof(serveraddr)); printf("\nReceiving message from server.\n");
//steps involved in defining the serveraddress. bzero((char*)&serveraddr,sizeof(serveraddr)); serveraddr.sin_family=AF_INET; serveraddr.sin_port=htons(5015); serveraddr.sin_addr.s_addr=INADDR_ANY;
//binding the socket to the operating system. bind(serversocket,(sockaddr*)&serveraddr,sizeof(serveraddr));
//receiving message from the client. recvfrom(serversocket,message,sizeof(message),0,(sockaddr*)&clientaddr,&len);
printf("\nConnection received from client.\n");
printf("\nThe client has send:\t%s\n",message);
printf("\nSending message to the client.\n");
//sending message to the client. sendto(serversocket,"YOUR MESSAGE RECEIVED.",sizeof("YOUR MESSAGE RECEIVED."),0,(sockaddr*)&clientaddr,sizeof(clientaddr));
close(serversocket);}
Output
Department Of Computer Science BM II College Of Engineering, Sasthamcotta96
Network-OS Lab Manual
Client
Algorithm
* The different processes involved in a udp client process are........
1.Create a datagram socket.
2.Receive/Send message to the server.
3.Close the socket.
Program
/* Program to demonstrate the creation and usage of datagram sockets.
* This module acts as a udp client which sends and receives messages from a udp server.
* This module should be compiled into different folder using the command 'c++ udpclient.cpp -o b' and execute using './b'
* For execution the 'udpserver' module should be executed first then this module.
//steps involved in the server address creation. bzero((char*)&serveraddr,sizeof(serveraddr)); len=sizeof(serveraddr); serveraddr.sin_family=AF_INET; serveraddr.sin_port=htons(5015); server=gethostbyname("127.0.0.1"); bcopy((char*)server->h_addr,(char*)&serveraddr.sin_addr.s_addr,sizeof(server->h_addr)); printf("\nPRESS ENTER TO START THE CONNECTION PROCESS.\n"); fgets(message,2,stdin); printf("\nSending message for server connection\n");
//sending message. sendto(clientsocket,"HI I AM CLIENT...",sizeof("HI I AM CLIENT...."),0,(sockaddr*)&serveraddr,sizeof(serveraddr));
//sending request for windowsize. printf("\nSending request for window size.\n"); sendto(serversocket,"REQUEST FOR WINDOWSIZE.",sizeof("REQUEST FOR WINDOWSIZE."),0,(sockaddr*)&clientaddr,sizeof(clientaddr));
//obtaining windowsize. printf("\nWaiting for the windowsize.\n"); recvfrom(serversocket,(char*)&windowsize,sizeof(windowsize),0,(sockaddr*)&clientaddr,&len); cls(); printf("\nThe windowsize obtained as:\t%d\n",windowsize);
printf("\nObtaining packets from network layer.\n"); printf("\nTotal packets obtained:\t%d\n",(totalpackets=windowsize*5)); printf("\nTotal frames or windows to be transmitted:\t%d\n",(totalframes=5));
//sending details to client. printf("\nSending total number of packets.\n"); sendto(serversocket,(char*)&totalpackets,sizeof(totalpackets),0,(sockaddr*)&clientaddr,sizeof(clientaddr)); recvfrom(serversocket,req,sizeof(req),0,(sockaddr*)&clientaddr,&len);
Department Of Computer Science BM II College Of Engineering, Sasthamcotta105
Network-OS Lab Manual
printf("\nSending total number of frames.\n"); sendto(serversocket,(char*)&totalframes,sizeof(totalframes),0,(sockaddr*)&clientaddr,sizeof(clientaddr)); recvfrom(serversocket,req,sizeof(req),0,(sockaddr*)&clientaddr,&len); printf("\nPRESS ENTER TO START THE PROCESS.\n"); fgets(req,2,stdin); cls();
//starting the process of sending while( i<totalpackets) {
//initialising the transmit buffer. bzero((char*)&f1,sizeof(f1)); printf("\nInitialising the transmit buffer.\n"); printf("\nThe frame to be send is %d with packets:\t",framessend); buffer=i; j=0;
//sending the frame. sendto(serversocket,(char*)&f1,sizeof(f1),0,(sockaddr*)&clientaddr,sizeof(clientaddr));
//Waiting for the acknowledgement. printf("\nWaiting for the acknowledgement.\n"); recvfrom(serversocket,(char*)&acknowledgement,sizeof(acknowledgement),0,(sockaddr*)&clientaddr,&len); cls();
//Checking acknowledgement of each packet. j=0; k=0; l=buffer; while(j<windowsize && l<totalpackets) { if(acknowledgement.acknowledge[j]==-1) { printf("\nNegative acknowledgement received for packet: %d\n",f1.packet[j]);
Department Of Computer Science BM II College Of Engineering, Sasthamcotta106
//establishing the connection. printf("\nSending request to the client.\n"); sendto(clientsocket,"HI I AM CLIENT.",sizeof("HI I AM CLIENT."),0,(sockaddr*)&serveraddr,sizeof(serveraddr));
printf("\nWaiting for reply.\n"); recvfrom(clientsocket,req,sizeof(req),0,(sockaddr*)&serveraddr,&len); printf("\nThe server has send:\t%s\n",req);
//accepting window size from the user. printf("\nEnter the window size:\t"); scanf("%d",&windowsize);
//sending the window size. printf("\n\nSending the window size.\n");
Department Of Computer Science BM II College Of Engineering, Sasthamcotta110
//collecting details from server. printf("\nWaiting for the server response.\n"); recvfrom(clientsocket,(char*)&totalpackets,sizeof(totalpackets),0,(sockaddr*)&serveraddr,&len); printf("\nThe total packets are:\t%d\n",totalpackets); sendto(clientsocket,"RECEIVED.",sizeof("RECEIVED."),0,(sockaddr*)&serveraddr,sizeof(serveraddr));
recvfrom(clientsocket,(char*)&totalframes,sizeof(totalframes),0,(sockaddr*)&serveraddr,&len); printf("\nThe total frames/windows are:\t%d\n",totalframes); sendto(clientsocket,"RECEIVED.",sizeof("RECEIVED."),0,(sockaddr*)&serveraddr,sizeof(serveraddr));
//starting the process. printf("\nStarting the process of receiving.\n"); while(i<totalpackets) {
//initialising the receive buffer. printf("\nInitialising the receive buffer.\n"); printf("\nThe expected frame is %d with packets: ",framesreceived); j=0; buffer=i; while(j<windowsize && i<totalpackets) { printf("%d ",i); i++; j++; }
printf("\n\nWaiting for the frame.\n");//accepting the frame.
recvfrom(clientsocket,(char*)&f1,sizeof(f1),0,(sockaddr*)&serveraddr,&len); printf("\nReceived frame %d\n\nEnter -1 to send negative acknowledgement for the following packets.\n",framesreceived);
//sending acknowledgement to the server. sendto(clientsocket,(char*)&acknowledgement,sizeof(acknowledgement),0,(sockaddr*)&serveraddr,sizeof(serveraddr)); cls(); }
printf("\nAll frames received successfully.\n\nClosing connection with the server.\n"); close(clientsocket);}
Output
Department Of Computer Science BM II College Of Engineering, Sasthamcotta112
Network-OS Lab Manual
Department Of Computer Science BM II College Of Engineering, Sasthamcotta113
Network-OS Lab Manual
SELECTIVE REPEAT REQUEST PROTOCOL
Server
Algorithm
* The algorithm for this process is as............................
1. Start.
2. Establish connection (recommended UDP)
3. Accept the window size from the client(should be <=40)
4. Accept the packets from the network layer.
5. Calculate the total frames/windows required.
6. Send the details to the client(totalpackets,totalframes.)
7. Initialise the transmit buffer.
8. Built the frame/window depending on the windowsize.
Department Of Computer Science BM II College Of Engineering, Sasthamcotta114
Network-OS Lab Manual
9. Transmit the frame.
10. Wait for the acknowledgement frame.
11. Check for the acknowledgement of each packet and repeat the
process for the packet for which the negative acknowledgement isreceived.
Else continue as usual.
12. Increment the frame count and repeat steps 7 to 12 until all packets are
transmitted.
13. Close the connection.
14.Stop.
Program
/* Program to demonstrate the working of 'SELECTIVE REPEAT PROTOCOL'.
* This module act as a server which initially establishes a connection with the client, sends
packets to it (using sliding window protocol),receives acknowledgement and retransmits
the packets for which negative acknowledgement is received (using selective repeat
protocol).
* It uses an UDP connection for the whole process.
* It uses two structures viz. 'frame' to design the frames/window to be transmitted and
'ack' to accept the acknowledgement.
* Here -1 is referred to as negative acknowledgement while all the other integers as
positive acknowledgement.
* The initial process are similar to that defined in the sliding window server process.
* NOTE: -> This module can be compiled using the command 'c++
selectiverepeat_server.cpp' and executed using './a.out'
-> The server module should be compiled and executed first.
Department Of Computer Science BM II College Of Engineering, Sasthamcotta115
//sending request for windowsize. printf("\nSending request for window size.\n"); sendto(serversocket,"REQUEST FOR WINDOWSIZE.",sizeof("REQUEST FOR WINDOWSIZE."),0,(sockaddr*)&clientaddr,sizeof(clientaddr));
//obtaining windowsize. printf("\nWaiting for the windowsize.\n"); recvfrom(serversocket,(char*)&windowsize,sizeof(windowsize),0,(sockaddr*)&clientaddr,&len); cls(); printf("\nThe windowsize obtained as:\t%d\n",windowsize);
printf("\nObtaining packets from network layer.\n"); printf("\nTotal packets obtained:\t%d\n",(totalpackets=windowsize*5)); printf("\nTotal frames or windows to be transmitted:\t%d\n",(totalframes=5));
//sending details to client. printf("\nSending total number of packets.\n"); sendto(serversocket,(char*)&totalpackets,sizeof(totalpackets),0,(sockaddr*)&clientaddr,sizeof(clientaddr)); recvfrom(serversocket,req,sizeof(req),0,(sockaddr*)&clientaddr,&len); printf("\nSending total number of frames.\n"); sendto(serversocket,(char*)&totalframes,sizeof(totalframes),0,(sockaddr*)&clientaddr,sizeof(clientaddr)); recvfrom(serversocket,req,sizeof(req),0,(sockaddr*)&clientaddr,&len); printf("\nPRESS ENTER TO START THE PROCESS.\n"); fgets(req,2,stdin); cls();
j=0; l=0; //starting the process of sending while( l<totalpackets) {
//initialising the transmit buffer. bzero((char*)&f1,sizeof(f1)); printf("\nInitialising the transmit buffer.\n"); printf("\nThe frame to be send is %d with packets:\t",framessend);
//Builting the frame.
Department Of Computer Science BM II College Of Engineering, Sasthamcotta117
Network-OS Lab Manual
for(m=0;m<j;m++) {
//including the packets for which negative acknowledgement was received. printf("%d ",repacket[m]); f1.packet[m]=repacket[m]; }
//sending the frame. sendto(serversocket,(char*)&f1,sizeof(f1),0,(sockaddr*)&clientaddr,sizeof(clientaddr));
//Waiting for the acknowledgement. printf("\nWaiting for the acknowledgement.\n"); recvfrom(serversocket,(char*)&acknowledgement,sizeof(acknowledgement),0,(sockaddr*)&clientaddr,&len); cls();
//Checking acknowledgement of each packet. j=0; k=0; m=0; n=l; while(m<windowsize && n<totalpackets) { if(acknowledgement.acknowledge[m]==-1) { printf("\nNegative acknowledgement received for packet: %d\n",f1.packet[m]); k=1; repacket[j]=f1.packet[m]; j++; } else { l++; } m++; n++; }
if(k==0)
Department Of Computer Science BM II College Of Engineering, Sasthamcotta118
Network-OS Lab Manual
{ printf("\nPositive acknowledgement received for all packets within the frame: %d\n",framessend); }
framessend++; printf("\nPRESS ENTER TO PROCEED......\n"); fgets(req,2,stdin); cls(); }
printf("\nAll frames send successfully.\n\nClosing connection with the client.\n"); close(serversocket);}
Output
Department Of Computer Science BM II College Of Engineering, Sasthamcotta119
Network-OS Lab Manual
Client
Algorithm
* The algorithm for this module process is as........................
1. Start.
2. Establish a connection.(recommended UDP)
3. Send the windowsize on server request.
4. Accept the details from the server(totalpackets,totalframes).
5. Initialise the receive buffer with the expected packets.
6. Accept the frame/window from the server.
7. Check for validity of the packets and construct the acknowledgement frame
depending on the validity.(Here the acknowledgement is accepeted from the
users)
Department Of Computer Science BM II College Of Engineering, Sasthamcotta120
Network-OS Lab Manual
8. Depending on the acknowledgement frame readjust the process.
9. Increment the framecount and repeat steps 5-9 until all packets are received.
10. Close the connection.
11. Stop.
Program
/* Program to demonstrate the working of 'SELECTIVE REPEAT PROTOCOL'.
* This module acts as a client which establishes a connection with the server, sends the
windowsize, accepts the frames and then sends acknowledgement for each packet wihin
the given frame.
* The connection used is UDP and the window size is taken from the user(should be<=40)
* It uses two structures viz. 'frame' for accepting the frames send by the server and 'ack' for
sending the acknowledgement.
* Here the acknowledgement for each packet is accepted from the user. The user can enter -1
for negative acknowledgement or any other integer for positive acknowledgement.
* NOTE: This module can be compiled using the command 'c++ selectiverepeat_server.cpp –
o b' and executed using the command './b'
-> Always compile and execute the server module first.
//establishing the connection. printf("\nSending request to the client.\n"); sendto(clientsocket,"HI I AM CLIENT.",sizeof("HI I AM CLIENT."),0,(sockaddr*)&serveraddr,sizeof(serveraddr));
printf("\nWaiting for reply.\n"); recvfrom(clientsocket,req,sizeof(req),0,(sockaddr*)&serveraddr,&len); printf("\nThe server has send:\t%s\n",req);
//accepting window size from the user. printf("\nEnter the window size:\t"); scanf("%d",&windowsize);
//sending the window size. printf("\n\nSending the window size.\n"); sendto(clientsocket,(char*)&windowsize,sizeof(windowsize),0,(sockaddr*)&serveraddr,sizeof(serveraddr)); cls();
Department Of Computer Science BM II College Of Engineering, Sasthamcotta122
Network-OS Lab Manual
//collecting details from server. printf("\nWaiting for the server response.\n"); recvfrom(clientsocket,(char*)&totalpackets,sizeof(totalpackets),0,(sockaddr*)&serveraddr,&len); printf("\nThe total packets are:\t%d\n",totalpackets); sendto(clientsocket,"RECEIVED.",sizeof("RECEIVED."),0,(sockaddr*)&serveraddr,sizeof(serveraddr));
recvfrom(clientsocket,(char*)&totalframes,sizeof(totalframes),0,(sockaddr*)&serveraddr,&len); printf("\nThe total frames/windows are:\t%d\n",totalframes); sendto(clientsocket,"RECEIVED.",sizeof("RECEIVED."),0,(sockaddr*)&serveraddr,sizeof(serveraddr));
//starting the process. printf("\nStarting the process of receiving.\n"); j=0; l=0; while(l<totalpackets) {
//initialising the receive buffer. printf("\nInitialising the receive buffer.\n"); printf("\nThe expected frame is %d with packets: ",framesreceived); for(m=0;m<j;m++) {
//readjusting for packets with negative acknowledgement. printf("%d ",repacket[m]); } while(j<windowsize && i<totalpackets) { printf("%d ",i); i++; j++; }
printf("\n\nWaiting for the frame.\n");//accepting the frame.
recvfrom(clientsocket,(char*)&f1,sizeof(f1),0,(sockaddr*)&serveraddr,&len); printf("\nReceived frame %d\n\nEnter -1 to send negative acknowledgement for the following packets.\n",framesreceived);
//constructing the acknowledgement frame. j=0; m=0; k=l;
Department Of Computer Science BM II College Of Engineering, Sasthamcotta123
//sending acknowledgement to the server. sendto(clientsocket,(char*)&acknowledgement,sizeof(acknowledgement),0,(sockaddr*)&serveraddr,sizeof(serveraddr)); cls(); }
printf("\nAll frames received successfully.\n\nClosing connection with the server.\n"); close(clientsocket);}
Output
Department Of Computer Science BM II College Of Engineering, Sasthamcotta124
Network-OS Lab Manual
SLIDING WINDOW PROTOCOL
Department Of Computer Science BM II College Of Engineering, Sasthamcotta125
Network-OS Lab Manual
Server
Algorithm
* The algorithm for the sliding window server is as..........
1.Start
2.Establish connection with the client.(UDP/TCP recommended UDP)
3.Accept the window size from the client.
4.Accept the packets from the network layer.
5.Combine packets to form frame/window.(depending on window size.)
6.Initialise the transmit buffer.
7.Send the frame and wait for the acknowledgement.
8.If a negative acknowledgement is received repeat the transmission of the
previous frame.
Else increment the frame to be transmitted.
9.Repeat steps 5 to 8 until all packet are transmitted successfully.
10.Close the connection.
11.Stop.
Program
/* Program to demonstrate the working of 'SLIDING WINDOW PROTOCOL'
* This module act as a server module which transmits the packets to the client.
* The server initially establishes connection with the client then accepts the window
size(should be always<=40).
* Then it calculates the total no. of packets by multiplying the window size with 5
(assumption: totalpackets=windowsize*5).
* Then frames are prepared depending upon the window size,transmits it to the client and
waits for the acknowledgement.
* If a negative (-1) acknowledgement is received the frame is transmitted again, else the next
Department Of Computer Science BM II College Of Engineering, Sasthamcotta126
Network-OS Lab Manual
frame is transmitted.
NOTE: Here only a single acknowledgement is considered for all the packets within a given
frame.
*NOTE: -> Compile this module using the command 'c++
slidingwindowserver.cpp'. To execute use './a.out'.
//structure definition for defining the frame.struct frame{ int packet[40];};
int main(){ int serversocket; sockaddr_in serveraddr,clientaddr; socklen_t len; int windowsize,totalpackets,totalframes,framessend=0,i=0,j=0,buffer,acknowledgement; frame f1; char req[50];
//sending request for windowsize. printf("\nSending request for window size.\n"); sendto(serversocket,"REQUEST FOR WINDOWSIZE.",sizeof("REQUEST FOR WINDOWSIZE."),0,(sockaddr*)&clientaddr,sizeof(clientaddr));
//obtaining windowsize. printf("\nWaiting for the windowsize.\n"); recvfrom(serversocket,(char*)&windowsize,sizeof(windowsize),0,(sockaddr*)&clientaddr,&len); cls(); printf("\nThe windowsize obtained as:\t%d\n",windowsize);
printf("\nObtaining packets from network layer.\n"); printf("\nTotal packets obtained:\t%d\n",(totalpackets=windowsize*5)); printf("\nTotal frames or windows to be transmitted:\t%d\n",(totalframes=5));
//sending details to client. printf("\nSending total number of packets.\n"); sendto(serversocket,(char*)&totalpackets,sizeof(totalpackets),0,(sockaddr*)&clientaddr,sizeof(clientaddr)); recvfrom(serversocket,req,sizeof(req),0,(sockaddr*)&clientaddr,&len); printf("\nSending total number of frames.\n"); sendto(serversocket,(char*)&totalframes,sizeof(totalframes),0,(sockaddr*)&clientaddr,sizeof(clientaddr)); recvfrom(serversocket,req,sizeof(req),0,(sockaddr*)&clientaddr,&len); printf("\nPRESS ENTER TO START THE PROCESS.\n"); fgets(req,2,stdin); cls();
//starting the process of sending while(framessend<totalframes) { printf("\nInitialising the transmit buffer.\n"); printf("\nThe frame to be send is %d with packets:\t",framessend); j=0; buffer=i;
//preparing the frame. while(j<windowsize && i<totalpackets) {
Department Of Computer Science BM II College Of Engineering, Sasthamcotta128
//sending frame. sendto(serversocket,(char*)&f1,sizeof(f1),0,(sockaddr*)&clientaddr,sizeof(clientaddr)); printf("\nWaiting for the acknowledgement.\n");
//waiting for the acknowledgement. recvfrom(serversocket,(char*)&acknowledgement,sizeof(int),0,(sockaddr*)&clientaddr,&len); cls();
//cheching the acknowledgement. if(acknowledgement==-1) { printf("\nNegative acknowledgement received for frame %d\n",framessend); printf("\nRetransmitting the frame.\n"); i=buffer; }
else { printf("\nPositive acknowledgement received for frame %d.\n",framessend); framessend++; } printf("\nPRESS ENTER TO PROCEED......\n"); fgets(req,2,stdin); cls(); }
printf("\nAll frames send successfully.\n\nClosing connection with the client.\n"); close(serversocket);}
Output
Department Of Computer Science BM II College Of Engineering, Sasthamcotta129
Network-OS Lab Manual
Client
Algorithm
Department Of Computer Science BM II College Of Engineering, Sasthamcotta130
Network-OS Lab Manual
* The algorithm for the client process is as............
1.Start.
2.Establish a connection with the server.(recommended UDP.)
3.Send the window size on server request.
4.Accept the details from the server.(totalpackets,totalframes.)
5.Initialise the receive buffer with the expected frame and packets.
6.Accept the frame and check for its validity.
7.Send positive or negative acknowledgement as required.
8.Repeat steps 5 to 7 until all packets are received.
9.Close the connection with the server.
10.Stop.
Program
/* Program to demonstrate the working of 'SLIDING WINDOW PROTOCOL.'
* This module act as client which accepts the packets from the server.
* The client initially establishes a connection with the server and then on request from the server sends the window size to the server.
NOTE: Here the window size is taken from the user. The user can input any valid number <=40.
* It also collects details such as the total packets and total frames from the server.
* It then receives the frames from the server for which it sends acknowledgement.
NOTE: Here the acknowledgement is accepted from the user. The user can input -1 for negative acknowledgement and 1 or any other number for positive acknowledgement.
//inculsion#include<iostream>#include<stdio.h>
Department Of Computer Science BM II College Of Engineering, Sasthamcotta131
printf("\nSending request to the client.\n"); sendto(clientsocket,"HI I AM CLIENT.",sizeof("HI I AM CLIENT."),0,(sockaddr*)&serveraddr,sizeof(serveraddr));
//accepting the window request. printf("\nWaiting for reply.\n"); recvfrom(clientsocket,req,sizeof(req),0,(sockaddr*)&serveraddr,&len); printf("\nThe server has send:\t%s\n",req);
//taking the window size from the user. printf("\nEnter the window size:\t"); scanf("%d",&windowsize);
//sending the window size. printf("\n\nSending the window size.\n"); sendto(clientsocket,(char*)&windowsize,sizeof(windowsize),0,(sockaddr*)&serveraddr,sizeof(serveraddr));
Department Of Computer Science BM II College Of Engineering, Sasthamcotta132
Network-OS Lab Manual
cls();
//collecting details from server. printf("\nWaiting for the server response.\n"); recvfrom(clientsocket,(char*)&totalpackets,sizeof(totalpackets),0,(sockaddr*)&serveraddr,&len); printf("\nThe total packets are:\t%d\n",totalpackets); sendto(clientsocket,"RECEIVED.",sizeof("RECEIVED."),0,(sockaddr*)&serveraddr,sizeof(serveraddr));
recvfrom(clientsocket,(char*)&totalframes,sizeof(totalframes),0,(sockaddr*)&serveraddr,&len); printf("\nThe total frames/windows are:\t%d\n",totalframes); sendto(clientsocket,"RECEIVED.",sizeof("RECEIVED."),0,(sockaddr*)&serveraddr,sizeof(serveraddr));
//starting the process. printf("\nStarting the process of receiving.\n"); while(framesreceived<totalframes) {
//initialising the receive buffer. printf("\nInitialising the receive buffer.\n"); printf("\nThe expected frame is %d with packets: ",framesreceived); j=0; buffer=i; while(j<windowsize && i<totalpackets) { printf("%d ",i); i++; j++; }
printf("\n\nWaiting for the frame.\n");
//receiving the frame. recvfrom(clientsocket,(char*)&f1,sizeof(f1),0,(sockaddr*)&serveraddr,&len); printf("\nReceived frame %d\n\nEnter -1 to send negative acknowledgement\n",framesreceived);
//taking acknowledgement from the user. scanf("%d",&acknowledgement); if(acknowledgement==-1) { i=buffer; } else {
Department Of Computer Science BM II College Of Engineering, Sasthamcotta133
Network-OS Lab Manual
framesreceived++; }
//sending acknowledgement to the server. sendto(clientsocket,(char*)&acknowledgement,sizeof(int),0,(sockaddr*)&serveraddr,sizeof(serveraddr)); cls(); }
printf("\nAll frames received successfully.\n\nClosing connection with the server.\n"); close(clientsocket);}
Output
Department Of Computer Science BM II College Of Engineering, Sasthamcotta134
Network-OS Lab Manual
FILE TRANSFER PROTOCOL
Theory
Department Of Computer Science BM II College Of Engineering, Sasthamcotta135
Network-OS Lab Manual
The FTP protocol is used to access files by FTP, the internet”s file transfer protocol.
Ftp has been around more than two decades and is well entrenched. Numerous FTP servers
all over the world allow people anywhere on the internet to log in and download whatever
files have been placed on the FTP server. The Web does not change this; it just makes
obtaining files by FTP easier, as FTP has a somewhat arcane interface.
It is possible to access a local file as a web page, either by using the file protocol or
more simply by just naming it. This approach is similar to using FTP but does not require
having a server. Of course, it works only for files not remote ones.
Server
Algorithm
* The algorithm for ftp server can be summerised as...................
1. Start.
2. Establish a tcp socket.
3. Listen over the socket.
4. Accept a connection.
5. Obtain the filename from the client.
6. Read the file.
7. Send it to the client.
8. Close the connection.
9. Stop.
Program
/* Program to demonstrate the implementation of ftp protocol.
* This module act as a ftp module, which accepts the filename, reads the file and sends it to
Department Of Computer Science BM II College Of Engineering, Sasthamcotta136
Network-OS Lab Manual
the client.
* This module establishes a tcp connection with the client.
* NOTE:
1. The file to be transfered should be in the same directory where this module is stored.
2. If the file does not exist the program might terminate abnormally.
3. The error handling routine has not been provided. It is assumed that everything would be
perfect.
* This program can be compiled using 'c++ simpleftpserver.cpp' and executed './a.out'
Department Of Computer Science BM II College Of Engineering, Sasthamcotta137
Network-OS Lab Manual
len=sizeof(clientaddr);
listen(serversocket,5); printf("\nWaiting for the connection\n"); clientsocket=accept(serversocket,(sockaddr*)&clientaddr,&len); printf("\nConnection obtained.\n");
read(clientsocket,filename,sizeof(filename));
printf("\nThe read filename is:\t%s\n",filename); printf("\nReading the file.\n");
printf("\nTrying to connect to the server.\n"); connect(clientsocket,(sockaddr*)&serveraddr,sizeof(serveraddr)); printf("\nConnected to the server.\n");
//waiting for the request. printf("\nWaiting for the request from the client.\n"); recvfrom(serversocket,request,sizeof(request),0,(sockaddr*)&clientaddr,&len); printf("The request received is:\t%s",request);
printf("\nPRESS ENTER TO SEND THE RESPONSE.\n"); fgets(request,2,stdin);
Department Of Computer Science BM II College Of Engineering, Sasthamcotta144
Network-OS Lab Manual
printf("\nSending the 220:SERVICE READY COMMAND.\n"); strcpy(request,"220:SERVICE READY."); sendto(serversocket,request,sizeof(request),0,(sockaddr*)&clientaddr,len);
//waiting for the first command
printf("Waiting for the next request."); recvfrom(serversocket,request,sizeof(request),0,(sockaddr*)&clientaddr,&len); cls(); printf("\nThe client has send:\t%s\n",request);
printf("\nPRESS ENTER TO SEND THE RESPONSE.\n"); fgets(request,2,stdin); printf("\nSending the POSITIVE COMPLETION REPLY:250 REQUEST COMMAND COMPLETED.\n"); strcpy(request,"250:REQUEST COMMAND COMPLETED."); sendto(serversocket,request,sizeof(request),0,(sockaddr*)&clientaddr,sizeof(clientaddr));
//waiting for second command. printf("\nWaiting for the next request.\n"); recvfrom(serversocket,request,sizeof(request),0,(sockaddr*)&clientaddr,&len); cls(); printf("\nThe client has send:\t%s\n",request); strcpy(from,request);
printf("\nPRESS ENTER TO SEND THE RESPONSE.\n"); fgets(request,2,stdin); printf("\nSending the POSITIVE COMPLETION REPLY:250\n"); strcpy(request,"250:REQUEST COMMAND COMPLETED."); sendto(serversocket,request,sizeof(request),0,(sockaddr*)&clientaddr,sizeof(clientaddr));
//waiting for the third command. printf("\nWaiting for the next request.\n"); recvfrom(serversocket,request,sizeof(request),0,(sockaddr*)&clientaddr,&len); cls(); printf("\nThe client has send:\t%s\n",request); strcpy(to,request);
printf("\nPRESS ENTER TO SEND THE RESPONSE.\n"); fgets(request,2,stdin); printf("\nSending the POSITIVE COMPLETION REPLY:250\n"); strcpy(request,"250:REQUEST COMMAND COMPLETED."); sendto(serversocket,request,sizeof(request),0,(sockaddr*)&clientaddr,sizeof(clientaddr));
//waiting for the fourth command. printf("\nWaiting for the next request.\n");
Department Of Computer Science BM II College Of Engineering, Sasthamcotta145
Network-OS Lab Manual
recvfrom(serversocket,request,sizeof(request),0,(sockaddr*)&clientaddr,&len); cls(); printf("\nThe client has send:\t%s\n",request);
printf("\nPRESS ENTER TO SEND THE RESPONSE.\n"); fgets(request,2,stdin); printf("\nSending the 354:START MAIL INPUT.\n"); strcpy(request,"354:START MAIL INPUT."); sendto(serversocket,request,sizeof(request),0,(sockaddr*)&clientaddr,sizeof(clientaddr));
//waiting for the fifth command. printf("\nWaiting for the mail\n"); recvfrom(serversocket,request,sizeof(request),0,(sockaddr*)&clientaddr,&len); strcpy(mail,request);
cls(); printf("\n\n\n\t\t\tTHE DETAILS INCLUDE:\n"); printf("\n\n\t\t%s",from); printf("\n\n\t\t%s",to); printf("\n\n\t\tMAIL:%s",mail); printf("\n\n\nSEARCHING FOR THE RECIPIENT AND MESSAGE PASSED FOR SENDING.");
printf("\nPRESS ENTER TO SEND THE RESPONSE.\n"); fgets(request,2,stdin); printf("\nSending the POSITIVE COMPLETION REPLY:250\n"); strcpy(request,"250 REQUEST COMMAND COMPLETED."); sendto(serversocket,request,sizeof(request),0,(sockaddr*)&clientaddr,sizeof(clientaddr));
//waiting for the quit command. printf("\nWaiting for the next request.\n"); recvfrom(serversocket,request,sizeof(request),0,(sockaddr*)&clientaddr,&len); cls(); printf("\nThe client has send:\t%s\n",request);
printf("\nPRESS ENTER TO SEND THE RESPONSE.\n"); fgets(request,2,stdin); printf("\nSending the 221:SERVICE CLOSING.\n"); strcpy(request,"221:SERVICE CLOSING."); sendto(serversocket,request,sizeof(request),0,(sockaddr*)&clientaddr,sizeof(clientaddr));
len=sizeof(serveraddr); printf("\nEnter the FROM address:\n"); fgets(from,sizeof(from),stdin);
printf("\nEnter the TO address:\n"); fgets(to,sizeof(to),stdin);
printf("\nEnter the MAIL:\n"); fgets(mail,sizeof(mail),stdin);
cls();
Department Of Computer Science BM II College Of Engineering, Sasthamcotta150
Network-OS Lab Manual
//smtp request printf("\nPRESS ENTER TO BEGIN THE FIRST PROCESS.\n"); fgets(request,2,stdin);
printf("\nSending SMTP REQUEST to the server.\n"); strcpy(request,"SMTP REQUEST."); sendto(clientsocket,request,sizeof(request),0,(sockaddr*)&serveraddr,sizeof(serveraddr));
printf("\nWaiting for the server response.\n"); recvfrom(clientsocket,request,sizeof(request),0,(sockaddr*)&serveraddr,&len); cls(); printf("\nThe server has send:\t%s\n",request);
//sending helo request printf("\nPRESS ENTER TO SEND THE FIRST COMMAND.\n"); fgets(request,2,stdin);
printf("\nSending the HELO command\n"); strcpy(request,"HELO"); sendto(clientsocket,request,sizeof(request),0,(sockaddr*)&serveraddr,sizeof(serveraddr));
printf("\nWaiting for the server response.\n"); recvfrom(clientsocket,request,sizeof(request),0,(sockaddr*)&serveraddr,&len); cls(); printf("\nThe server has send:\t%s\n",request);
//sending mail from command. printf("\nPRESS ENTER TO BEGIN THE SECOND COMMAND.\n"); fgets(request,2,stdin);
printf("\nSending the MAIL FROM request.\n"); strcpy(request,"MAIL FROM:"); strcat(request,from); sendto(clientsocket,request,sizeof(request),0,(sockaddr*)&serveraddr,sizeof(serveraddr));
printf("\nWaiting for the server response.\n"); recvfrom(clientsocket,request,sizeof(request),0,(sockaddr*)&serveraddr,&len); cls(); printf("\nThe server has send:\t%s\n",request);
//sending rcpt command. printf("\nPRESS ENTER TO BEGIN THE THIRD COMMAND.\n"); fgets(request,2,stdin);
printf("\nSending the RCPT TO request.\n");
Department Of Computer Science BM II College Of Engineering, Sasthamcotta151
printf("\nWaiting for the server response.\n"); recvfrom(clientsocket,request,sizeof(request),0,(sockaddr*)&serveraddr,&len); cls(); printf("\nThe server has send:\t%s\n",request);
//sending data command. printf("\nPRESS ENTER TO BEGIN THE FOURTH COMMAND.\n"); fgets(request,2,stdin);
printf("\nSending the DATA request.\n"); strcpy(request,"DATA:"); sendto(clientsocket,request,sizeof(request),0,(sockaddr*)&serveraddr,sizeof(serveraddr));
printf("\nWaiting for the server response.\n"); recvfrom(clientsocket,request,sizeof(request),0,(sockaddr*)&serveraddr,&len); cls(); printf("\nThe server has send:\t%s\n",request);
//sending mail. printf("\nPRESS ENTER TO BEGIN SENDING THE MAIL.\n"); fgets(request,2,stdin);
printf("\nSending the mail.\n"); strcpy(request,mail); sendto(clientsocket,request,sizeof(request),0,(sockaddr*)&serveraddr,sizeof(serveraddr));
printf("\nWaiting for the server response.\n"); recvfrom(clientsocket,request,sizeof(request),0,(sockaddr*)&serveraddr,&len); cls(); printf("\nThe server has send:\t%s\n",request);
//sending the quit command. printf("\nPRESS ENTER TO BEGIN THE LAST COMMAND.\n"); fgets(request,2,stdin);
printf("\nSending the QUIT request.\n"); strcpy(request,"QUIT:"); sendto(clientsocket,request,sizeof(request),0,(sockaddr*)&serveraddr,sizeof(serveraddr));
printf("\nWaiting for the server response.\n"); recvfrom(clientsocket,request,sizeof(request),0,(sockaddr*)&serveraddr,&len);
Department Of Computer Science BM II College Of Engineering, Sasthamcotta152
Network-OS Lab Manual
cls(); printf("\nThe server has send:\t%s\n",request);
printf("\n\nCLIENT CLOSING DOWN.\n\n");
close(clientsocket);}
Output
Department Of Computer Science BM II College Of Engineering, Sasthamcotta153
Network-OS Lab Manual
Department Of Computer Science BM II College Of Engineering, Sasthamcotta154
Network-OS Lab Manual
REMOTE PROCEDURE CALL
Theory
When a process on machine 1 calls a procedure on machine 2, the calling process on
1 is suspended and execution of called procedure takes place on 2.Information can be
transported from the caller to callee in the parmeters and can come back in the procedure
result.No message passing is visible to the programmer. This technique is known as
RPC(Remote Procedure Call) and has become the basis for many networking applications.
Traditionally, the calling procedure is known as the client and the called procedure is known
as the server, and we will use those names here too.
The idea behind RPC is to make a remote procedure call lok as much as possible like
local one. In the simplest form, to call a remoter procedure, the client program must be bound
with a small library procedure, called the client stub, that represents the server procedure in
the server stub. These procedures hide the fact that the procedure call from the client to sever
is not local.
Program
Department Of Computer Science BM II College Of Engineering, Sasthamcotta155