ADAM’S ENGINEERING COLLEGE

(Affiliated to JNTUH, Approved by AICTE & Accredited by NBA)
Seetarampatnam, Paloncha-507115 Khammam (Dist)

Network Programming Lab Manual
Department of Computer Science & Engineering

Prepared By: G.Sampath Kumar. M.Tech, M.I.S.T.E, M.C.S.I.
Asst. Professor

JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD.

1

JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITY HYDERABAD IV Year B.Tech. CSE -I Sem T P 0 3 NETWORK PROGRAMMING LAB Objectives:  To teach students various forms of IPC through Unix and socket Programming

C 2

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 file Week7. 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) Pipes b) FIFO a) Named Pipes Half Duplex --------------------------------------------------------------------------------------------------------------------half Duplex.h #define HALF_DUPLEX "/tmp/halfduplex" #define MAX_BUF_SIZE 255 --------------------------------------------------------------------------------------------------------------------hd_server.c #include <stdio.h> #include <errno.h> #include <ctype.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include "half_duplex.h" /* For name of the named-pipe */ #include <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 <stdio.h> #include <errno.h> #include <ctype.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <string.h> #include <fcntl.h> #include "half_duplex1.h" /* For name of the named-pipe */ #include <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

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

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

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

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

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

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

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

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

out msgsend [sampath@localhost msgque]$ .out msgrec [sampath@localhost msgque]$ .Execution Steps: [sampath@localhost msgque]cc message_send.c [sampath@localhost msgque]mv a.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./msgrec & [1] 2907 [sampath@localhost msgque]$ Did you get this? --------------------------------------------------------------------------------------------------------------------- 14 .c [sampath@localhost msgque]mv a./msgsend msgget: Calling msgget(0x4d2.

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

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.Execution steps: [sampath@localhost ipc]$cc shared_mem.c [sampath@localhost ipc]$ .

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

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

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

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

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

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

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

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

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

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

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

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

/tcpclient 127. Compiling and running server.c [root@localhost week7and8]# mv a.} printf("String : %s sent to server \n". root@localhost week7and8]# cc tcpservselect01.1 13153 enter sentence to end enter #abcd# String : abcd sent to server --------------------------------------------------------------------------------------------------------------------- 29 .out tcpservselect1 [root@localhost week7and8]# . root@localhost week7and8]# .0. } /****************************************************************************/ Execution Steps: b) Concurrent Server Application Using Select./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.buffer).0.

servaddr.h> #include <string.h> #include <fcntl. (struct sockaddr *) &servaddr.sin_port = htons(SERV_PORT).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.h> #include <arpa/inet.Week8. char **argv) { int k. Design a TCP concurrent server to echo given set of sentences using poll functions tcpservpoll01. connfd. listenfd = socket(AF_INET.c #include <stdlib. sockfd. int nready.sin_addr. struct sockaddr_in cliaddr. sizeof(servaddr)). 5).s_addr = htonl(INADDR_ANY).h> #include <stdio. sizeof(servaddr)). ssize_t n. 0). 30 . bzero(&servaddr. char line[MAXLINE].h> #include <limits. servaddr.h> #include <netinet/in. bind(listenfd. listen(listenfd. i.h> #include <sys/types.sin_family = AF_INET. servaddr. socklen_t clilen.h> #include <poll.h> #include <sys/stat. struct pollfd client[OPEN_MAX].h> #include <sys/socket. maxi. servaddr. listenfd. SOCK_STREAM.h> #include <errno.

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

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

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

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

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

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

h> <string.h> <signal.h> <stdlib.h> <errno.h> <fcntl.h> <arpa/inet.c /****************************************************************************** * FILENAME : uechos.h> #define BUFSIZE 512 #define MYPORT 11710 #define MAXNAME 100 int main(int C.Week9. struct sockaddr_in 37 .c * DESCRIPTION:Contains Code for a echo server .h> <netinet/in.out * Copyright 2007 Aricent ******************************************************************************/ #include #include #include #include #include #include #include #include #include #include #include <stdio.h> <sys/socket. udp_server.h> <sys/wait. that will accept data * from a client process and sends that data back to client. 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.h> <sys/types.n. char **V ) { int sd.ret. using UDP * Invoke the Executable as a.

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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.