Network Programming Lab Manual Department of Computer Science & Engineering

NETWORK PROGRAMMING LAB Objectives: To teach students various forms of IPC through Unix and socket Programming Recommended Systems/Software Requirements: Intel based desktop PC with minimum of 166 MHZ or faster processor with at least 64 MB RAM and 100 MB free disk space LAN Connected Any flavor of Unix / Linux Week1. Implement the following forms of IPC. a)Pipes b)FIFO Week2. Implement file transfer using Message Queue form of IPC Week3. Write a program to create an integer variable using shared memory concept and increment the variable simultaneously by two processes. Use semaphores to avoid race conditions Week4. Design TCP iterative Client and server application to reverse the given input sentence Week5. Design TCP iterative Client and server application to reverse the given input sentence Week6. Design TCP client and server application to transfer Week7. file Design a TCP concurrent server to convert a given text into upper case using multiplexing system call “select” Week8. Design a TCP concurrent server to echo given set of sentences using poll functions Week9. Design UDP Client and server application to reverse the given input sentence Week10 Design UDP Client server to transfer a file Week11 Design using poll client server application to multiplex TCP and UDP requests for converting a given text into upper case. Week12 Design a RPC application to add and subtract a given pair of integers Reference Book: 1. Advance UNIX Programming Richard Stevens, Second Edition Pearson Education 2. Advance UNIX Programming, N.B. Venkateswarlu, BS Publication. 2

Week1. Implement the following forms of IPC. a) Pipesb) FIFO a) Named Pipes Half Duplex -------------------------------------------------------------------------------------------------------------------half Duplex.h #define HALF_DUPLEX"/tmp/halfduplex" #define MAX_BUF_SIZE 255 -------------------------------------------------------------------------------------------------------------------hd_server.c #include #include #include #include #include #include #include #include #include <stdio.h> <errno.h> <ctype.h> <unistd.h> <sys/types.h> <sys/stat.h> <fcntl.h> "half_duplex.h" /* For name of the named-pipe */ <stdlib.h>

int main(int argc, char *argv[]) { int fd, ret_val, count, numread; char buf[MAX_BUF_SIZE]; /* Create the named - pipe */ ret_val = mkfifo(HALF_DUPLEX, 0666); if ((ret_val == -1) && (errno != EEXIST)) { perror("Error creating the named pipe\n"); exit (1); } /* Open the pipe for reading */ fd = open(HALF_DUPLEX, O_RDONLY); /* Read from the pipe */ numread = read(fd, buf, MAX_BUF_SIZE);

3

buf[numread] = '0'; printf("Half Duplex Server : Read From the pipe : %s\n", buf); /* Convert to the string to upper case */ count = 0; while (count < numread) { buf[count] = toupper(buf[count]); count++; }

printf("Half Duplex Server : Converted String : %s\n", buf); } -------------------------------------------------------------------------------------------------------------------halfduplex1.h #define HALF_DUPLEX"/tmp/halfduplex1" #define MAX_BUF_SIZE 255 -------------------------------------------------------------------------------------------------------------------hd_client.c #include #include #include #include #include #include #include #include #include #include <stdio.h> <errno.h> <ctype.h> <unistd.h> <sys/types.h> <sys/stat.h> <string.h> <fcntl.h> "half_duplex1.h" /* For name of the named-pipe */ <stdlib.h>

int main(int argc, char *argv[]) { int fd; /* Check if an argument was specified. */ if (argc != 2) { printf("Usage : %s <string to be sent to the server>n", argv[0]); exit (1); }

4

/* Open the pipe for writing */ fd = open(HALF_DUPLEX, O_WRONLY); /* Write to the pipe */ write(fd, argv[1], strlen(argv[1])); } Execution Steps: 1.Named Pipes: a) Half Duplex. 1. Run the server: % cc hd_server.c % mv a.out hd_server %./hd_server & The server program will block here, and the shell will return control to the command line. 2. Run the client: % cc hd_client % mv a.out hd_client %./hd_client hello 3. The server prints the string read and terminates:

Output:Half Duplex Server : Read From the pipe : hello Half Duplex Server : Converted String : HELLO --------------------------------------------------------------------------------------------------------------------

5

} /* Open the first named pipe for reading */ rdfd = open(NP1. wrfd.h" /* For name of the named-pipe */ #include <stdlib. numread. count. 0666). exit (1). ret_val. char *argv[]) { int rdfd. char buf[MAX_BUF_SIZE].h> #include <ctype. 0666). O_RDONLY). exit (1). 6 .b) Named Pipe: Full Duplex: full duplex.h> #include <fcntl. /* Create the first named . if ((ret_val == -1) && (errno != EEXIST)) { perror("Error creating the named pipe").c #include <stdio.h> #include "fullduplex.h> #include <errno.h> #include<string.h> int main(int argc. if ((ret_val == -1) && (errno != EEXIST)) { perror("Error creating the named pipe").h #define NP1"/tmp/np1" #define NP2"/tmp/np2" #define MAX_BUF_SIZE 255 -------------------------------------------------------------------------------------------------------------------fd_server.pipe */ ret_val = mkfifo(NP1.h> #include <sys/stat.h> #include <sys/types. } ret_val = mkfifo(NP2.

buf. /* Read from the first pipe */ numread = read(rdfd. buf). buf[numread] = '0'. } -------------------------------------------------------------------------------------------------------------------- 7 . printf("Full Duplex Server : Read From the pipe : %s\n". O_WRONLY). count++. } /* * * Write the converted string back to the second * * pipe * */ write(wrfd./* Open the second named pipe for writing */ wrfd = open(NP2. buf. strlen(buf)). /* Convert to the string to upper case */ count = 0. while (count < numread) { buf[count] = toupper(buf[count]). MAX_BUF_SIZE).

exit (1). char *argv[]) { int wrfd. /* Check if an argument was specified.h> #include "fullduplex. O_WRONLY).h> int main(int argc.h> #include <sys/types. rdfd.h> #include <ctype. O_RDONLY). char rdbuf[MAX_BUF_SIZE]. } 8 . rdbuf). strlen(argv[1])). MAX_BUF_SIZE).fd_client. printf("Full Duplex Client : Read From the Pipe : %s\n". rdbuf. /* Read from the pipe */ numread = read(rdfd.c #include <stdio.h" /* For name of the named-pipe */ #include <stdlib. */ if (argc != 2) { printf("Usage : %s <string to be sent to the server>n".h> #include <sys/stat. rdbuf[numread] = '0'. } /* Open the first named pipe for writing */ wrfd = open(NP1. argv[1]. numread.h> #include <errno.h> #include<string. argv[0]). /* Open the second named pipe for reading */ rdfd = open(NP2.h> #include <fcntl. /* Write to the pipe */ write(wrfd.

9 .out fd_client The client prints the following: Full Duplex Client : Read From the pipe : HELLO %. 1.c % mv a.The client program will send the string to server and block on the read to await the server's response./fd_server & The server program will block here.out fd_server %.The server Full Duplex Server : Read From the pipe : hello % mv a.Run the client: % cc fd_client prints the following: 4.Run the server: % cc fd_server. 2./fd_client hello ----------------------------------------------------------------------------------------------------------3. and the shell will return control to the command line.Execution Steps: b) Full Duplex.

h> <sys/msg. key_t key. } message_buf.h> #define MSGSZ 128 /* * Declare the message structure. msgflg). */ typedef struct msgbuf { long mtype. (void) fprintf(stderr. Implement file transfer using Message Queue form of IPC message_send.c -.h> <stdio. */ key = 1234. msgflg )) < 0) { perror("msgget"). main() { int msqid. size_t buf_length.h> <sys/ipc. message_buf sbuf. /* * Get the message queue id for the * "name" 1234. key.creating and sending to a simple message queue #include #include #include #include #include <sys/types. "\nmsgget: Calling msgget(%#lx. char mtext[MSGSZ]. which was created by * the server.Week2. 10 .h> <string. if ((msqid = msgget(key.\ %#o)\n". int msgflg = IPC_CREAT | 0666.

msqid). sbuf. (void) strcpy(sbuf.mtext.exit(1). "Did you get this?"). } else (void) fprintf(stderr."msgget: msgget succeeded: msqid = %d\n". msqid). sbuf. } else printf("Message: \"%s\" Sent\n". IPC_NOWAIT) < 0) { printf ("%d. buf_length). %d. (void) fprintf(stderr. buf_length. sbuf.mtype. msqid).mtext.mtext). (void) fprintf(stderr. &sbuf."msgget: msgget succeeded: msqid = %d\n". buf_length = strlen(sbuf. */ if (msgsnd(msqid. /* * We'll send message type 1 */ sbuf. msqid. exit(0). } ----------------------------------------------------------------------------------------------------------- 11 . %d\n"."msgget: msgget succeeded: msqid = %d\n".mtype = 1. exit(1).mtext) + 1 . perror("msgsnd"). /* * Send a message. %s.

which was created by * the server. exit(1). } /* * Receive an answer of message type 1. */ typedef struct msgbuf { long mtype. MSGSZ. main() { int msqid. */ key = 1234.receiving the above message #include #include #include #include <sys/types. char mtext[MSGSZ].message_rec.c -.h> 128 #define MSGSZ /* * Declare the message structure.h> <sys/msg. } message_buf. if ((msqid = msgget(key. */ if (msgrcv(msqid. /* * Get the message queue id for the * "name" 1234. 1. key_t key.h> <stdio. 0666)) < 0) { perror("msgget").h> <sys/ipc. 0) < 0) { perror("msgrcv"). message_buf rbuf. &rbuf. 12 .

} /* * Print the answer. } 13 . */ printf("%s\n". exit(0).exit(1). rbuf.mtext).

Execution Steps: [sampath@localhost msgque]cc message_send.c [sampath@localhost msgque]mv a.c [sampath@localhost msgque]mv a./msgsend msgget: Calling msgget(0x4d2.out msgsend [sampath@localhost msgque]$ .01666) msgget: msgget succeeded: msqid = 0 msgget: msgget succeeded: msqid = 0 msgget: msgget succeeded: msqid = 0 Message: "Did you get this?" Sent [sampath@localhost msgque]cc message_rec.out msgrec [sampath@localhost msgque]$ ./msgrec & [1] 2907 [sampath@localhost msgque]$ Did you get this? ----------------------------------------------------------------------------------------------------------- 14 .

sleep(5). printf("Shared Memory ID=%u". *shared). shared).h> int main(void) { pid_t pid. sleep(1).h> #include <unistd. (void *) 0. printf("Child value=%d\n". Write a program to create an integer variable using shared memory concept and increment the variable simultaneously by two processes. shmctl(shmid. printf("Child pointer %u\n". sleep(2). if (fork() == 0) { /* Child */ /* Attach to shared memory and print the pointer */ shared = shmat(shmid.Week3. } } 15 . int *shared. IPC_CREAT | 0666). *shared). printf("Parent value=%d\n". Use semaphores to avoid race conditions #include <sys/types.h> #include <sys/shm. *shared=42.h> #include <errno. *shared). *shared=1. *shared). IPC_RMID. 0). printf("Parent pointer %u\n". (void *) 0. sizeof(int). shared). printf("Child value=%d\n". } else { /* Parent */ /* Attach to shared memory and print the pointer */ shared = shmat(shmid.h> #include <sys/ipc. 0). printf("Parent value=%d\n". 0).h> #include <string.shmid). /* pointer to the shm */ int shmid. shmid = shmget(IPC_PRIVATE.

Execution steps: [sampath@localhost ipc]$cc shared_mem.out Shared Memory ID=65537Child pointer 3086680064 Child value=1 Shared Memory ID=65537Parent pointer 3086680064 Parent value=1 Parent value=42 Child value=42 ----------------------------------------------------------------------------------------------------------- 16 ./a.c [sampath@localhost ipc]$ .

char *).h> <unistd.Week4.h> <arpa/inet. char *V[] ) { intlistensocket.h> <string.h> <sys/wait.out *Copyright 2007 Aricent ************************************************************** **************/ #include #include #include #include #include #include #include #include #include #include #include <stdio.h> #define MYPORT 13154 /*The port users will be connecting to*/ void readstring(int.cliaddr. struct sockaddr_in serveraddress.retbind. Design TCP iterative Client and server application to reverse the given input sentence Week6.h> <sys/types.h> <sys/socket. char buf[100].h> <errno.c *DESCRIPTION:Contains Code for a server.that will accept *a string from a client process .h> <fcntl. int main(int C.(Shows a typical ITERATIVE SERVER ) *Invoke the Executable as a. Design TCP iterative Client and server application to reverse the given input sentence Week5. Design TCP client and server application to transfer file tcpserver. prints the string and the *IP Address of the client .h> <stdlib.databuf[1024].h> <netinet/in. 17 .c / ************************************************************** ************* *FILENAME :demoserver. socklen_t len.connectionsocket.

sizeof(serveraddress) ).&cliaddr. memset(&serveraddress. len=sizeof(cliaddr).buf. sizeof(serveraddress)). exit(1).(struct sockaddr*)&serveraddress. exit(1).listensocket = socket(AF_INET. printf("Finished Serving One Client\n"). /*Beginning of the Main Server Processing Loop*/ for (.. } printf("Connection from %s\n".5). } serveraddress.) { printf("Server:I am waiting-----Start of Main Loop\n").sin_addr.sin_family = AF_INET./*ADDRESS*/ retbind=bind(listensocket. serveraddress. SOCK_STREAM./*PORT NO*/ serveraddress. readstring(connectionsocket . } listen(listensocket. 0.sizeof(buf))). continue. if (listensocket < 0 ) { perror("socket" ). if (connectionsocket < 0) { if (errno == EINTR) printf("Interrupted system call ??").&len). inet_ntop(AF_INET. 0 ).sin_port = htons(MYPORT).sin_addr. connectionsocket=accept(listensocket. (struct sockaddr*)&cliaddr. close(connectionsocket).s_addr = htonl(INADDR_ANY). } } 18 . /*Check the return value of bind for error*/ if(-1==retbind) { perror("BIND ERROR\n"). databuf).

char rev[50]. } /**********************************************************************/ ----------------------------------------------------------------------------------------------------------- 19 .i. for(i=k-1.i--) temp[a++]=fname[i]. //strcpy(temp.fname). void readstring( *NOTESconnectionsocket. int k.k++). //len=k.b.temp[50]. printf("enter the string\n")./*Socket Descriptor*/ int : No Error Checking is done .(fname + pointer). printf("\nrev is %s\n".i>=0. } fname[pointer]='\0'. k=strlen(fname). //for(k=0. while ((n=read(connectionsocket./ *********************************************************** ********* *FUNCTION NAME:readstring *DESCRIPTION: Reads the string sent by the client over the *socket and stores it in the array fname . to be populated by the string from client*/ *RETURNS :void / **************************************************************** *********************************************************** ****/ **********/ { int pointer=0. int len=0. temp). a=0. char *fname) /*Array .1024))>0) { pointer=pointer+n. temp[a]='\0'.a. printf("Server :Received %s\n " .n.temp1[50].temp[k]!=0.fname).

fd.out IPAddress PortNo string *Copyright 2007 Aricent *************************************************************** **************/ #include<stdio. exit(0). char *V[] ) { intsd. char text[100]. SOCK_STREAM.h> #include<stdlib. *Invoke the Executable as a.c *DESCRIPTION:Contains Code for a client that will send a string *to a server process and exits.h> #define MAXBUFFER 1024 void sendstring(int . char c. int main( int C.h> #include<netinet/in.h> #include<sys/types.c / *************************************************************** ************ *FILENAME : democlient.h> #include<sys/socket. exit(0). } //if (V[3] == NULL ) { 20 .h> #include<unistd.h> #include<string. struct sockaddr_in serveraddress. sd = socket( AF_INET.h> #include<fcntl. 0 ).h> #include<sys/stat.h> #include<errno. if( sd < 0 ) { perror( "socket" ). char *).h> #include<arpa/inet. } if (V[2] == NULL ) { printf ("PL specify the server's Port No \n"). } if (V[1] == NULL ) { printf ("PL specfiy the server's IP Address \n").tcpclient. exit( 1 ). int i=0.

while (byteswritten<n) { written=write(sd . 0. 21 . sizeof(serveraddress) ).text). strcpy(buffer . buffer+byteswritten. return 0.//PORT NO serveraddress./*Socket Descriptor*/ char *fname) /*Array Containing the string */ / ************************************************************** ***********/ {int n . while(1) { c=getchar(). fname).(n-byteswritten)). n=strlen(buffer).//ADDRESS if (connect(sd. byteswritten=0 . // } memset( &serveraddress. *NOTES : No Error Checking is done . } printf("enter sentence to end enter #"). // serveraddress. if(c=='#') break. *RETURNS :void ************************************************************* ***********/ void sendstring( int sd. } / ************************************************************* *********** *FUNCTION NAME:sendstring *DESCRIPTION: sends a string over the socket . sizeof(serveraddress))<0) { printf("Cannot Connect to server"). written . close(sd).sin_port = htons(atoi(V[2])).s_addr = inet_addr(V[1]). sendstring(sd. text[i++]=c. exit(1). serveraddress. exit(0).sin_family = AF_INET.sin_addr.(struct sockaddr*)&serveraddress. byteswritten+=written. } text[i]='\0'.// printf ("PL specfiy the string to be send to the server \n"). char buffer[MAXBUFFER].

} / ************************************************************* ***************/ 22 .buffer).} printf("String : %s sent to server \n".

c [user@localhost week9]$ mv a.c [user@localhost week9]$ mv a.0.out tcpserver [user@localhost week9]$ .0.1 13153 enter sentence to end enter #Network Programming# String : Network Programming sent to server 23 . [user@localhost week9]$ cc tcpserver.0. Compiling and running client.TCP a) Client Server Application./tcpclient 127.Execution Steps: 2.Compiling and running server.out tcpclient [user@localhost week9]$./tcpserver Server:I am waiting-----Start of Main Loop Rev string is gnimmargorP krowteN Finished Serving One Client Connection from 127.1 Server:I am waiting-----Start of Main Loop enter the string 2. 1.0. Server :Received Network Programming [user@localhost week9]$ cc tcpclient.

intnready.h> #include<sys/time.s_addr = htonl(INADDR_ANY). struct sockaddr_in cliaddr. listenfd = socket(AF_INET.h> #include<arpa/inet.h> #include<fcntl. 24 . socklen_tclilen.h> #include<sys/stat.Week7. listenfd.h> #include<stdlib.h> #define MAXLINE 100 #define SERV_PORT 13153 int main(int argc.h> #include<errno. charline[MAXLINE]. fd_setrset. maxi. Design a TCP concurrent server to convert a given text into upper case using multiplexing system call “select” tcpservselect01.h> #include<sys/select.h> #include<string. connfd. sizeof(servaddr)). exit(1).sin_addr. 0). (struct sockaddr *) &servaddr. } bzero(&servaddr.sin_port= htons(SERV_PORT). sizeof(servaddr)).c #include<stdio. ssize_tn. if (listenfd < 0 ) { perror("socket" ). allset.sin_family= AF_INET.h> #include<netinet/in. bind(listenfd. servaddr.h> #include<sys/socket.h> #include<unistd. servaddr. servaddr. char **argv) { intk. client[FD_SETSIZE]. servaddr.i. maxfd. sockfd.buf[100]. SOCK_STREAM.h> #include<sys/types.

i < FD_SETSIZE.sin_port)). maxi = -1. /* add new descriptor to set */ if (connfd > maxfd) maxfd = connfd. &allset). ntohs(cliaddr. i < FD_SETSIZE. NULL./* structure assignment */ nready = select(maxfd+1. #endif for (i = 0. FD_ZERO(&allset).5). if (FD_ISSET(listenfd. } FD_SET(connfd. exit(0). buf. &cliaddr. NULL). &clilen). &allset). port %d\n". ) { printf("Server:I am waiting-----Start of Main Loop\n"). NULL. connfd = accept(listenfd.listen(listenfd. rset = allset. /* save descriptor */ break. NULL). &rset)) {/* new client connection */ clilen = sizeof(cliaddr). i++) if (client[i] < 0) { client[i] = connfd./* for select */ if (i > maxi) maxi = i. (struct sockaddr *) &cliaddr. } if (i == FD_SETSIZE) { printf("too many clients"). /* end fig01 */ /* initialize */ /* index into client[] array */ /* -1 indicates available entry */ /* include fig02 */ for ( .sin_addr. i++) client[i] = -1. . &rset. maxfd = listenfd. inet_ntop(AF_INET. #ifdef NOTDEF printf("new client: %s./* max index in client[] array */ if (--nready <= 0) 25 . for (i = 0. FD_SET(listenfd.

if (FD_ISSET(sockfd. write(sockfd. */ } /* no more readable descriptors for (i = 0.line[k]!='\0'. } else { printf("\n output at server\n"). n).continue. client[i] = -1. i <= maxi. line.toupper(line[k])).k++) printf("%c". &rset)) { if ( (n = read(sockfd. &allset). */ } } } } /* end fig02 */ ----------------------------------------------------------------------------------------------------------/* no more readable descriptors 26 . line. i++) { /* check all clients for data */ if ( (sockfd = client[i]) < 0) continue. MAXLINE)) == 0) { /*4connection closed by client */ close(sockfd). FD_CLR(sockfd. } if (--nready <= 0) break. for(k=0.

char *V[] ) #include<string.h> sd = socket( AF_INET.c / *************************************************************** ************ *FILENAME : democlient. int i=0. #define MAXBUFFER 1024 } if (V[2] == NULL ) { void sendstring(int . printf ("PL specify the server's Port No \n"). 0 ). SOCK_STREAM. char *).out IPAddress PortNo string *Copyright 2007 Aricent *************************************************************** **************/ #include<stdio.h> int main( int C.h> } if (V[1] == NULL ) { #include<fcntl. #include<arpa/inet.h> #include<stdlib.tcpclient.h> printf ("PL specfiy the server's IP Address \n"). *Invoke the Executable as a.h> #include<unistd. } //if (V[3] == NULL ) { 27 .h> char text[100].h> char c. #include<sys/socket. struct sockaddr_in serveraddress. exit( 1 ).h> { intsd. #include<sys/stat.h> #include<errno. if( sd < 0 ) { #include<netinet/in. exit(0).h> perror( "socket" ).fd. exit(0). #include<sys/types.c *DESCRIPTION:Contains Code for a client that will send a string *to a server process and exits.

n=strlen(buffer). sizeof(serveraddress))<0) { printf("Cannot Connect to server"). fname).// printf ("PL specfiy the string to be send to the server \n"). exit(1). *NOTES : No Error Checking is done . serveraddress. written . exit(0)./*Socket Descriptor*/ char *fname) /*Array Containing the string */ / ************************************************************** ***********/ {int n .sin_addr. byteswritten+=written.//ADDRESS if (connect(sd.sin_family = AF_INET. 28 .text). 0. } text[i]='\0'.(n-byteswritten)). while(1) { c=getchar(). sizeof(serveraddress) ). if(c=='#') break.(struct sockaddr*)&serveraddress. strcpy(buffer . text[i++]=c. char buffer[MAXBUFFER].//PORT NO serveraddress. } / ************************************************************** ********** *FUNCTION NAME:sendstring *DESCRIPTION: sends a string over the socket . buffer+byteswritten. return 0. // serveraddress.sin_port = htons(atoi(V[2])). close(sd). *RETURNS :void ************************************************************** **********/ void sendstring( int sd. while (byteswritten<n) { written=write(sd . } printf("enter sentence to end enter #"). byteswritten=0 . sendstring(sd. // } memset( &serveraddress.s_addr = inet_addr(V[1]).

out tcpservselect1 [root@localhost week7and8]# .c [root@localhost week7and8]# mv a.1 13153 enter sentence to end enter #abcd# String : abcd sent to server ----------------------------------------------------------------------------------------------------------- 29 .0.buffer)./tcpclient 127. root@localhost week7and8]# . } / ************************************************************* ***************/ Execution Steps: b) Concurrent Server Application Using Select. root@localhost week7and8]# cc tcpservselect01.0./tcpservselect1 Server:I am waiting-----Start of Main Loop Server:I am waiting-----Start of Main Loop output at server A B C DServer:I am waiting-----Start of Main Loop output at server A B C DServer:I am waiting-----Start of Main Loop Server:I am waiting-----Start of Main Loop Compiling and running Client.} printf("String : %s sent to server \n". Compiling and running server.

i. bzero(&servaddr.sin_family= AF_INET.h> #include<sys/types.sin_addr.Week8. charline[MAXLINE]. servaddr. socklen_tclilen. sockfd. struct pollfdclient[OPEN_MAX]. servaddr. listen(listenfd. SOCK_STREAM.h> #include<limits. maxi. (struct sockaddr *) &servaddr.c #include<stdlib. 5). connfd.h> #include<fcntl.h> #include<stdio.h> #include<sys/stat. struct sockaddr_in cliaddr.h> #include<errno. 0). char **argv) { intk. listenfd = socket(AF_INET.h> #define MAXLINE 100 #define SERV_PORT 13154 #define POLLRDNORM 5 #define INFTIM 5 #define OPEN_MAX 5 /* for OPEN_MAX */ int main(int argc. sizeof(servaddr)). ssize_tn.h> #include<string.h> #include<poll. intnready. listenfd.h> #include<netinet/in. servaddr.h> #include<sys/socket. servaddr.s_addr = htonl(INADDR_ANY). sizeof(servaddr)). Design a TCP concurrent server to echo given set of sentences using poll functions tcpservpoll01. bind(listenfd.sin_port= htons(SERV_PORT). 30 .h> #include<arpa/inet.

&clilen). } client[i].fd = connfd.fd = -1. } if (i == OPEN_MAX) { printf("too many clients"). if (i > maxi) maxi = i. i < OPEN_MAX. clilen)). client[0]. i <= maxi./* -1 indicates available entry */ maxi = 0. connfd = accept(listenfd. i < OPEN_MAX./* max index into client[] array */ /* include fig02 */ /* end fig01 */ for ( .events = POLLRDNORM. sock_ntop((struct sockaddr *) &cliaddr.fd = listenfd. exit(0).client[0]. if (--nready <= 0) continue. .revents & POLLRDNORM) { /* new client connection */ clilen = sizeof(cliaddr). #ifdef NOTDEF printf("new client: %s\n". if (client[0]. i++) client[i]. maxi+1.fd < 0) { client[i]. i++) if (client[i]. #endif for (i = 1.fd) < 0) 31 . (struct sockaddr *) &cliaddr. INFTIM). */ } /* save descriptor */ /* max index in client[] array */ /* no more readable descriptors for (i = 1.events = POLLRDNORM. i++) { /* check all clients for data */ if ( (sockfd = client[i]. break. for (i = 1. ) { nready = poll(client.

//write(sockfd. /*4connection reset by client */ close(sockfd). printf(" length=%d data = %s\n". k=strlen(line). if (client[i]. i). n). k. } if (--nready <= 0) break. #endif close(sockfd). } else{ printf("\n data from client is \n"). } else printf("readline error"). line. } else if (n == 0) { /*4connection closed by client */ #ifdef NOTDEF printf("client[%d] closed connection\n". line.revents & (POLLRDNORM | POLLERR)) { if ( (n = read(sockfd. client[i]. strcpy(line. i).fd = -1. */ } } } } /* end fig02 */ ---------------------------------------------------------------------------------------------------------------/* no more readable descriptors 32 .line).continue. client[i]. MAXLINE)) < 0) { #ifdef NOTDEF #endif if (errno == ECONNRESET) { printf("client[%d] aborted connection\n"." ").fd = -1.

h> #include<string. int main( int C.h> #include<arpa/inet.h> #include<errno.out IPAddress PortNo string *Copyright 2007 Aricent *************************************************************** **************/ #include<stdio. char text[100].h> #include<sys/types.c *DESCRIPTION:Contains Code for a client that will send a string *to a server process and exits.fd. sd = socket( AF_INET.h> #include<sys/stat. } //if (V[3] == NULL ) { 33 . 0 ). struct sockaddr_in serveraddress. int i=0. *Invoke the Executable as a. exit(0).h> #include<unistd. } if (V[2] == NULL ) { printf ("PL specify the server's Port No \n"). char *). exit( 1 ). SOCK_STREAM. exit(0). } if (V[1] == NULL ) { printf ("PL specfiy the server's IP Address \n"). char c.h> #include<stdlib.h> #define MAXBUFFER 1024 void sendstring(int .c / *************************************************************** ************ *FILENAME : democlient. char *V[] ) { intsd.democlient.h> #include<sys/socket.h> #include<netinet/in. if( sd < 0 ) { perror( "socket" ).h> #include<fcntl.

} / ********************************************************** ************** *FUNCTION NAME:sendstring *DESCRIPTION: sends a string over the socket . } printf("enter sentence to end enter #")./*Socket Descriptor*/ char *fname) /*Array Containing the string */ / ************************************************************** ***********/ {int n . serveraddress. 0. *RETURNS :void ********************************************************** **************/ void sendstring( int sd.//ADDRESS if (connect(sd. n=strlen(buffer). // serveraddress. sendstring(sd.text).//PORT NO serveraddress.s_addr = inet_addr(V[1]). byteswritten=0 . written . while(1) { c=getchar(). close(sd).sin_addr. strcpy(buffer . buffer+byteswritten. text[i++]=c. *NOTES : No Error Checking is done . sizeof(serveraddress) ). fname). while (byteswritten<n) { written=write(sd . return 0.sin_family = AF_INET.(struct sockaddr*)&serveraddress.(n-byteswritten)). 34 . exit(0). char buffer[MAXBUFFER].// printf ("PL specfiy the string to be send to the server \n"). // } memset( &serveraddress. exit(1).sin_port = htons(atoi(V[2])). sizeof(serveraddress))<0) { printf("Cannot Connect to server"). if(c=='#') break. } text[i]='\0'.

} / ************************************************************* ***************/ ---------------------------------------------------------------------------------------------------------- 35 .byteswritten+=written.buffer). } printf("String : %s sent to server \n".

/client 127. Compiling and running server.0.out client [root@localhost week8]# ./pollserv data from client is data = aaaaaaaaaaaaaaaaaaaaaaaa Compiling and running Client.c) Concurrent Server Application Using Poll. [root@localhost week8]# cc tcpservpoll01.1 13153 enter sentence to end enter #aaaaaaaaaaaaaaaaaaaaaaaa# String : aaaaaaaaaaaaaaaaaaaaaaaa sent to server ----------------------------------------------------------------------------------------------------------- 36 . [root@localhost week8]#cc democlient.c [root@localhost week8]# mv a.c [root@localhost week8]#mv a.0.out pollserv [root@localhost week8]# .

h> <stdlib. that will accept data *from a client process and sends that data back to client.h> <fcntl.c / ******************************************************************** ********** *FILENAME : uechos.Week9. char **V ) { intsd.h> <sys/wait. struct sockaddr_in 37 . using UDP *Invoke the Executable as a.h> <string.h> <signal.c *DESCRIPTION:Contains Code for a echo server .out *Copyright 2007 Aricent ******************************************************************** **********/ #include #include #include #include #include #include #include #include #include #include #include <stdio.h> <sys/types.n.h> <errno. Design UDP Client and server application to reverse the given input sentence Week10 Design UDP Client server to transfer a file Week11 Design using poll client server application to multiplex TCP and UDP requests for converting a given text into upper case.ret.h> <arpa/inet.h> #define BUFSIZE 512 #define MYPORT 11710 #define MAXNAME 100 int main(int C.h> <netinet/in.h> <sys/socket. udp_server.

sin_addr.n. printf("Data Received from %s\n".) { printf("I am waiting\n"). SOCK_DGRAM. 0 ).length).0.//IP ADDRESS ret=bind(sd. memset( &cliaddr.0. exit( 1 ). char clientname[MAXNAME]. } memset( &serveraddress.sizeof(clientname))). 0. serveraddress.datareceived[BUFSIZE].s_addr = htonl(INADDR_ANY).sizeof(serveraddress)).datareceived.(struct sockaddr*)&serveraddress.//PORT NO serveraddress. clientname. serveraddress. sizeof(cliaddr) ). sizeof(serveraddress) ). /*Received a datagram*/ length=sizeof(cliaddr).&cliaddr. 0.sin_addr.serveraddress.(struct sockaddr *)&cliaddr.BUFSIZE. } } ----------------------------------------------------------------------------------------------------------- 38 .. socklen_t length.datareceived).cliaddr. n=recvfrom(sd. /*Sending the Received datagram back*/ datareceived[n]='\0'. &length). exit(1). (struct sockaddr*)&cliaddr . if(ret<0) { perror("BIND FAILS"). sd = socket( AF_INET.datareceived. printf("I have received %s\n". inet_ntop(AF_INET.sin_port = htons(MYPORT).sin_family = AF_INET. sendto(sd. } for(. if( sd < 0 ) { perror( "socket" ).

h> #include<signal.h> #include<sys/socket. exit(0). struct sockaddr_in serveraddress.sig_usr). } if (NULL==argv[2]) { printf("Please enter the Port Number of the server\n"). exit(0).c / ******************************************************************* ******** *FILENAME : uechoc. int main( int C.out ServerIP ServerPort *Copyright 2007 Aricent ******************************************************************* *********/ #include<stdio. socklen_t len). int sockfd . struct sockaddr *server .h> #include<stdlib. void str_cli(FILE *fp .c *DESCRIPTION:Contains Code for a echo client . 39 .h> #include<arpa/inet.(UDP) *Invoke the Executable as a. signal(SIGINT.h> #define BUFSIZE 512 static void sig_usr(int).h> #include<fcntl. that will accept data *from the user(keyboard) and sens that data to a echo server process *and prints the received data back on the screen .sig_usr).h> #include<sys/types.h> #include<unistd. char *argv[] ) { intsd.h> #include<netinet/in.h> #include<errno.h> #include<string. /*Installing signal Handlers*/ signal(SIGPIPE.udp_client. if (NULL==argv[1]) { printf("Please enter the IP Address of the server\n").

serveraddress.(struct sockaddr *)&serveraddress. memset( &serveraddress. } 40 .sin_family = AF_INET. char *strctrl="RECEIVED CTRL-C FROM YOU".strlen(strpipe)). sizeof(serveraddress)). exit( 1 ). if( sd < 0 ) { perror( "socket" ).strpipe.ERROR". SOCK_DGRAM. if(signo==SIGPIPE) { write(1.sin_port = htons(atoi(argv[2])).//PORT NO } serveraddress.strctrl. sizeof(serveraddress) ).//ADDRESS printf("Client Starting service\n"). str_cli(stdin.} sd = socket( AF_INET. } else if(signo==SIGINT) { write(1. 0 ). } / *********************************************************** ************* *FUNCTION NAME:sig_usr *DESCRIPTION: Signal Handler for Trappinf SIGPIPE *NOTES : No Error Checking is done . exit(1).s_addr = inet_addr(argv[1]).sin_addr. exit(1). serveraddress. 0. printf("Enter Data For the server\n").strlen(strctrl)). *RETURNS :void *********************************************************** *************/ static void sig_usr( int signo) /*Signal Number*/ / *********************************************************** *************/ { char *strpipe="RECEIVED SIGPIPE .sd .

&rset). (struct sockaddr*)&serveraddr. fd_set rset. } if(FD_ISSET(fileno(fp) . inet_ntop(AF_INET.NULL).servername[100]. *RETURNS :void ****************************************************************** ******/ void str_cli(FILE *fp. printf("Data Received from server %s:\n".NULL. write(1. socklen_t slen.&rset.recvbuf.sin_addr. select(maxdes. n=recvfrom(sockfd. & rset)) { 41 .n). for(..){ FD_SET(fileno(fp) .socklen_t length)/*Connection Socket */ / ******************************************************************** ***/ { int maxdes./*Here to be used as stdin as argument*/ int sockfd . struct sockaddr_in serveraddr.&serveraddr.recvbuf. char sendbuf[BUFSIZE] .} / ****************************************************************** ****** *FUNCTION NAME:str_cli *DESCRIPTION: Main Client Processing (Select waits for readiness of *connection socket or stdin *NOTES : No Error Checking is done . maxdes=(sockfd>fileno(fp)?sockfd+1:fileno(fp)+1).BUFSIZE.&slen). &rset).sizeof(servername))). struct sockaddr *to . if(FD_ISSET(sockfd . FD_SET(sockfd . recvbuf[BUFSIZE] . FD_ZERO(&rset). & rset)) { slen=sizeof(serveraddr).0. servername. printf("Enter Data For the server\n").NULL.n.

BUFSIZE./*Reading data from the keyboard*/ fgets(sendbuf.n.to. n = strlen (sendbuf). } /**************************************************************************/ ----------------------------------------------------------------------------------------------------------- 42 .sendbuf. printf("Data Sent To Server\n").0. /*Sending the read data over socket*/ } } sendto(sockfd.length).fp).

0.1 I have received abcd efgh rev is hgfe dcba I am waiting Compiling and running client.1: abcd efgh Enter Data For the server 43 .0.out udp_server [user@localhost week9]$ .0. user@localhost week9]$ cc udp_client./ udp_client 127.out udp_client [user@localhost week9]$ .5.c [user@localhost week9]$ mv a.0. [user@localhost week9]$ cc udp_server.c [user@localhost week9]$ mv a.1 11710 Client Starting service Enter Data For the server abcd efgh Data Sent To Server Data Received from server 127.0./ udp_server I am waiting Data Received from 127. Compiling and running server. UDP Client Server Application.0.

Week12 Design a RPC application to add and subtract a given pair of integers rpctime. ----------------------------------------------------------------------------------------------------------- 44 . } = 2000001.x***/ /******/ /*** SPECIFICATION FILE FOR RPC TO DEFINE SERVER PROCEDURE AND ARGUMENTS ***/ / ********************************************************************** program RPCTIME *******/ { version RPCTIMEVERSION { long GETTIME() = 1. } = 1.x / ********************************************************************** *******/ /*** rpctime.

#ifndef _RPCTIME_H_RPCGEN */ #define _RPCTIME_H_RPCGEN #include <rpc/rpc. extern long * gettime_1_svc(). caddr_t).h /* * Please do not edit this file. * It was generated using rpcgen. extern int rpctime_1_freeresult (SVCXPRT *. xdrproc_t. struct svc_req *). extern int rpctime_1_freeresult (). #else /* K&R C */ #define GETTIME 1 extern long * gettime_1(). extern long * gettime_1_svc(void *.h> #ifdef __cplusplus extern "C" { #endif #define RPCTIME 2000001 #define RPCTIMEVERSION 1 #if defined(__STDC__) || defined(__cplusplus) #define GETTIME 1 extern long * gettime_1(void *. CLIENT *). #endif /* K&R C */ #ifdef __cplusplus } #endif #endif /* !_RPCTIME_H_RPCGEN */ -------------------------------------------------------------------------------------------------------------------- 45 .rpctime.

INCLUDING. LOSS OF USE.c***/ /******/ / /* ************************************************************** * This is sample code ***************/ generated by rpcgen. WHETHER IN CONTRACT. SPECIAL. PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES. OR PROFITS. * These are only templates and you can use them * as a guideline for developing your own functions. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE. OR CONSEQUENTIAL * DAMAGES (INCLUDING. BUT NOT LIMITED TO. INDIRECT. OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY. */ #include "rpctime. EXEMPLARY. THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. Use may be in * whole or in part in accordance to the General Public License (GPL). INCIDENTAL.h" void rpctime_1(char *host) { CLIENT *clnt. STRICT * LIABILITY. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES. DATA. */ / ************************************************************** ***************/ /*** rpctime_client.rpctime_client /* rpctime_client. EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT.c * * Copyright (c) 2000 Sean Walton and Macmillan Publishers. BUT NOT LIMITED TO. 46 .

long *result_1. ctime(result_1)). argv[0]). exit (0). * It was generated using rpcgen. char *argv[]) { char *host.h> /* for memset */ 47 . *result_1. #ifndefDEBUG clnt_destroy (clnt). #ifndefDEBUG clnt = clnt_create (host. exit (1). RPCTIME. if (clnt == NULL) { clnt_pcreateerror (host). */ #include <memory. char *gettime_1_arg. } #endif /* DEBUG */ result_1 = gettime_1((void*)&gettime_1_arg. } else printf("%d |%s". #endif /* DEBUG */ } int main (int argc. rpctime_1 (host).c /* * Please do not edit this file. "call failed"). } rpctime_cntl. if (result_1 == (long *) NULL) { clnt_perror (clnt. } host = argv[1]. "udp"). RPCTIMEVERSION. if (argc < 2) { printf ("usage: %s server_host\n". clnt). exit (1).

memset((char *)&clnt_res. CLIENT *clnt) { static long clnt_res. } ----------------------------------------------------------------------------------------------------------- 48 . (caddr_t) argp. 0 }. 0. sizeof(clnt_res)).#include "rpctime. (caddr_t) &clnt_res. long * gettime_1(void *argp. TIMEOUT) != RPC_SUCCESS) { return (NULL). (xdrproc_t) xdr_void. (xdrproc_t) xdr_long. } return (&clnt_res). GETTIME. if (clnt_call (clnt.h" /* Default timeout can be changed using clnt_control() */ static struct timeval TIMEOUT = { 25.

THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. OR PROFITS. INCIDENTAL. */ / ************************************************************** ***************/ /*** rpctime_server. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE. Use may be in * whole or in part in accordance to the General Public License (GPL). struct svc_req *rqstp) { static long result.c /* rpctime_server. BUT NOT LIMITED TO. */ #include "rpctime.rpctime_server.h" long * gettime_1_svc(void *argp. EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. DATA. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES.c***/ /******/ / /* ************************************************************** * This is sample code ***************/ generated by rpcgen. OR CONSEQUENTIAL * DAMAGES (INCLUDING. INDIRECT. * These are only templates and you can use them * as a guideline for developing your own functions. WHETHER IN CONTRACT.c * * Copyright (c) 2000 Sean Walton and Macmillan Publishers. LOSS OF USE. INCLUDING. STRICT * LIABILITY. BUT NOT LIMITED TO. SPECIAL. OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY. EXEMPLARY. 49 . IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT. PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES.

} ----------------------------------------------------------------------------------------------------------- 50 .time(&result). return &result.

char *result. * It was generated using rpcgen. 51 . return. } argument.h> <rpc/pmap_clnt.h> <memory.h> <stdlib. 0. return. _xdr_result. struct svc_req *)) gettime_1_svc. local = (char *(*)(char *. (char *)NULL). struct svc_req *). switch (rqstp->rq_proc) { case NULLPROC: (void) svc_sendreply (transp. case GETTIME: _xdr_argument = (xdrproc_t) xdr_void. default: svcerr_noproc (transp). sizeof (argument)). #include */ #include #include #include #include #include #include #include "rpctime. xdrproc_t _xdr_argument.h> <netinet/in. register SVCXPRT *transp) { union { int fill.h> <string. break.h> #ifndef SIG_PF #define SIG_PF void(*)(int) #endif static void rpctime_1(struct svc_req *rqstp.h> <sys/socket.rpctime_svc. char *(*local)(char *.c /* * Please do not edit this file. _xdr_result = (xdrproc_t) xdr_long.h" <stdio. } memset ((char *)&argument. (xdrproc_t) xdr_void.

"svc_run returned"). (xdrproc_t) _xdr_argument. "%s". char **argv) exit (1). (caddr_t) &argument)) { svcerr_decode (transp). } return. } result = (*local)((char *)&argument. } svc_run (). "cannot create udp service.if (!svc_getargs (transp."). "%s". 0. (caddr_t) &argument)) { fprintf (stderr. if (transp == NULL) { fprintf (stderr. "cannot create tcp service. } transp = svctcp_create(RPC_ANYSOCK. RPCTIME."). RPCTIMEVERSION. "%s". exit(1). { register SVCXPRT *transp. rpctime_1. 52 . RPCTIMEVERSION. result)) { svcerr_systemerr (transp). RPCTIMEVERSION. RPCTIMEVERSION). } if (!svc_register(transp. "unable to register (RPCTIME. 0)."). udp). } if (!svc_register(transp. RPCTIME. int main (int argc. pmap_unset (RPCTIME. "%s". tcp). exit(1)."). } } if (!svc_freeargs (transp. "unable to register (RPCTIME. "%s". IPPROTO_TCP)) { fprintf (stderr. fprintf (stderr. exit(1). (xdrproc_t) _xdr_argument. rqstp). RPCTIMEVERSION. if (result != NULL && !svc_sendreply(transp. rpctime_1. if (transp == NULL) { fprintf (stderr. "unable to free arguments"). "%s". (xdrproc_t) _xdr_result. return. transp = svcudp_create(RPC_ANYSOCK). exit(1). IPPROTO_UDP)) { fprintf (stderr.

exit (1). /* NOTREACHED */ } ----------------------------------------------------------------------------------------------------------- 53 .

c files in the folder Step 2: [user@localhost $]$cc –c rpctime_client. rpctime_clnt.o -lnsl [root@localhost $]$.o rpctime_clnt.0.0.0./client 127.c. Step 1: [user@localhost $]$ rpcgen –C rpctime.h.o -lnsl Step 4: [user@localhost $]$cc –c rpctime_server.o Step 5: [user@localhost $]$cc –o server rpctime_server./client 127.x.1 1277628718 |Sun Jun 27 14:21:58 2010 54 .c –o rpctime_clien.o rpctime_svc. This creates rpctime. RPC Application./server & [1] 7610 [root@localhost $]$. rpctime_svc.1 1277628700 |Sun Jun 27 14:21:40 2010 [root@localhost $]$.0.6.c –o rpctime_server.o Step 3: [user@localhost $]$cc –o client rpctime_client.

Sign up to vote on this title
UsefulNot useful

Master Your Semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master Your Semester with a Special Offer from Scribd & The New York Times

Cancel anytime.