1

Swami Ramananda Tirtha Institute of Science & Technoloyg,Nalgonda
(Affiliated to JNTUH, Approved by AICTE & Accredited by NBA)

Network Programming Lab Manual B.Tech(IV/IV-I Sem)
Computer Science & Engineering Department

Prepared By: T.Madhu.B.E, M.Tech, M.I.S.T.E
Assoc. Professor

JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITYHYDERABAD.
JAWAHARLAL NEHRU TECHNOLOGICAL UNIVERSITYHYDERABAD IV Year B.Tech. CSE -I Sem T P C0 3 2 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 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.

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); 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); }

} /* Open the pipe for writing */ fd = open(HALF_DUPLEX. 2.h> int main(int argc. /* Write to the pipe */ write(fd.h> #include "half_duplex1.c $mv a.h> #include <fcntl. O_WRONLY). Run the server: $ cc hd_server. argv[0]). and the shell will return control to the command line. char *argv[]) { int fd. Named Pipes: a) Half Duplex./hd_client hello 3.h> #include <unistd.h" /* For name of the named-pipe */ #include <stdlib. /* Check if an argument was specified.c #include <stdio.h> #include <errno. 1.out hd_client $. strlen(argv[1])).halfduplex1.h> #include <string.out hd_server $ ./hd_server & The server program will block here. exit (1). The server prints the string read and terminates: Output:Half Duplex Server : Read From the pipe : hello Half Duplex Server : Converted String : HELLO -------------------------------------------------------------------------------------------------------------- . argv[1]. Run the client: $ cc hd_client $mv a.h> #include <ctype. } Execution Steps: 1.h> #include <sys/stat. */ if (argc != 2) { printf("Usage : %s <string to be sent to the server>n".h> #include <sys/types.h #define HALF_DUPLEX "/tmp/halfduplex1" #define MAX_BUF_SIZE 255 --------------------------------------------------------------------------------------------------------------hd_client.

h> #include <sys/stat. /* Read from the first pipe */ numread = read(rdfd.b) Named Pipe: Full Duplex: full duplex. while (count < numread) { buf[count] = toupper(buf[count]). wrfd.h> #include <fcntl.h> #include <sys/types.c #include <stdio. exit (1). char *argv[]) { int rdfd.h> int main(int argc. count++.h> #include "fullduplex.h> #include <ctype. } ret_val = mkfifo(NP2. 0666). char buf[MAX_BUF_SIZE]. 0666). /* Create the first named . printf("Full Duplex Server : Read From the pipe : %s\n". } /* * * Write the converted string back to the second * * pipe . exit (1). buf[numread] = '0'.pipe */ ret_val = mkfifo(NP1. buf). count. } /* Open the first named pipe for reading */ rdfd = open(NP1. numread. O_RDONLY). ret_val. if ((ret_val == -1) && (errno != EEXIST)) { perror("Error creating the named pipe").h> #include<string.h" /* For name of the named-pipe */ #include <stdlib. 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. 7 /* Open the second named pipe for writing */ wrfd = open(NP2. O_WRONLY). buf. MAX_BUF_SIZE).h> #include <errno. /* Convert to the string to upper case */ count = 0.

strlen(argv[1])).h> #include <sys/stat.c #include <stdio.h> #include <fcntl. char rdbuf[MAX_BUF_SIZE]. rdbuf[numread] = '0'. O_WRONLY).h> #include "fullduplex. } Execution Steps: b) Full Duplex. printf("Full Duplex Client : Read From the Pipe : %s\n". /* Open the second named pipe for reading */ rdfd = open(NP2. } /* Open the first named pipe for writing */ wrfd = open(NP1.c $mv a. /* Check if an argument was specified.h> #include <ctype. 2.h" /* For name of the named-pipe */ #include <stdlib. /* Write to the pipe */ write(wrfd.h> #include<string. argv[1]. 4. char *argv[]) { int wrfd. The server prints the following: Full Duplex Server : Read From the pipe : hello The client prints the following: . buf. Run the client: $ cc fd_client $mv a. rdbuf). exit (1). numread.} --------------------------------------------------------------------------------------------------------------fd_client. strlen(buf)).out fd_server $.h> #include <sys/types./fd_client hello 3.out fd_client $. and the shell will return control to the command line. argv[0]). O_RDONLY). rdfd./fd_server & The server program will block here. Run the server: $ cc fd_server. */ if (argc != 2) { printf("Usage : %s <string to be sent to the server>n". /* Read from the pipe */ numread = read(rdfd. MAX_BUF_SIZE).* */ write(wrfd. 1. rdbuf.h> int main(int argc.h> #include <errno. The client program will send the string to server and block on the read to await the server's response.

Full Duplex Client : Read From the pipe : HELLO -------------------------------------------------------------------------------------------------------------- .

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

* Send a message.c -. } message_buf.h> #include <stdio. */ if (msgrcv(msqid. buf_length.mtext.h> #define MSGSZ 128 /* * Declare the message structure. } /* * Print the answer. sbuf. %d. */ typedef struct msgbuf { long mtype. 0666)) < 0) { perror("msgget"). MSGSZ. %s. key_t key.mtype.receiving the above message #include <sys/types. } /* * Receive an answer of message type 1. perror("msgsnd"). 0) < 0) { perror("msgrcv"). */ if (msgsnd(msqid. */ key = 1234. main() { int msqid. } else printf("Message: \"%s\" Sent\n". . &rbuf. exit(1). buf_length). sbuf. msqid.h> #include <sys/msg. &sbuf. which was created by * the server. sbuf. %d\n".h> #include <sys/ipc. if ((msqid = msgget(key. char mtext[MSGSZ]. } --------------------------------------------------------------------------------------------------------------message_rec. IPC_NOWAIT) < 0) { printf ("%d. /* * Get the message queue id for the * "name" 1234. exit(0). exit(1). message_buf rbuf. 1.mtext). 13 exit(1).

*/ printf("%s\n". } Execution Steps: $ cc message_send.out msgsend $ .01666) msgget: msgget succeeded: msqid = 0 msgget: msgget succeeded: msqid = 0 msgget: msgget succeeded: msqid = 0 Message: "Did you get this?" Sent $ cc message_rec./msgrec & [1] 2907 $ Did you get this? --------------------------------------------------------------------------------------------------------------- .c $ mv a.mtext).c $ mv a.out msgrec $ . exit(0)./msgsend msgget: Calling msgget(0x4d2. rbuf.

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

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

int len=0. char rev[50]. connectionsocket=accept(listensocket.fname). } printf("Connection from %s\n". exit(1).. (struct sockaddr*)&cliaddr.sizeof(buf))).1024))>0) { pointer=pointer+n. /*Socket Descriptor*/ char *fname) /*Array ./*Check the return value of bind for error*/ if(-1==retbind) { perror("BIND ERROR\n"). printf("Finished Serving One Client\n").(fname + pointer).&len). if (connectionsocket < 0) { if (errno == EINTR) printf("Interrupted system call ??"). } fname[pointer]='\0'. * NOTES : No Error Checking is done .) { printf("Server:I am waiting-----Start of Main Loop\n").i. close(connectionsocket). inet_ntop(AF_INET.a. printf("Server :Received %s\n " .b. continue.n.&cliaddr. * RETURNS :void *********************************************************************/ void readstring( int connectionsocket.5). len=sizeof(cliaddr). . printf("enter the string\n").temp[50]. readstring(connectionsocket . } } 19 /******************************************************************** * FUNCTION NAME:readstring * DESCRIPTION: Reads the string sent by the client over the * socket and stores it in the array fname . int k. while ((n=read(connectionsocket.buf. /*Beginning of the Main Server Processing Loop*/ for (.temp1[50].sin_addr. databuf). to be populated by the string from client*/ /********************************************************************/ { int pointer=0. } listen(listensocket.

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

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

} printf("String : %s sent to server \n".out tcpclient $. $ cc tcpserver.0.1 13153 enter sentence to end enter #Network Programming# String : Network Programming sent to server .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.0.Compiling and running server. } / *************************************************************************** */ Execution Steps: 2. TCP a) Client Server Application.out tcpserver $ . Compiling and running client.c $ mv a.c $ mv a.0.0./tcpserver Server:I am waiting-----Start of Main Loop Connection from 127. $ cc tcpclient./tcpclient 127.buffer). 1.

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

NULL). &clilen). /* no more readable descriptors */ } for (i = 0./* include fig02 */ for ( . for(k=0. ) { printf("Server:I am waiting-----Start of Main Loop\n"). if (FD_ISSET(listenfd.k++) printf("%c". FD_CLR(sockfd. . /* for select */ if (i > maxi) maxi = i. } if (i == FD_SETSIZE) { printf("too many clients"). &cliaddr. &rset. i++) { /* check all clients for data */ if ( (sockfd = client[i]) < 0) continue. /* max index in client[] array */ if (--nready <= 0) continue. /* no more readable descriptors */ . &allset). NULL). &allset). i++) if (client[i] < 0) { client[i] = connfd. &rset)) { if ( (n = read(sockfd. write(sockfd. port %d\n". i <= maxi.toupper(line[k])). exit(0). NULL. if (FD_ISSET(sockfd. #ifdef NOTDEF printf("new client: %s. line. connfd = accept(listenfd.sin_addr. inet_ntop(AF_INET. client[i] = -1. buf. NULL. } FD_SET(connfd. /* structure assignment */ nready = select(maxfd+1. } else { printf("\n output at server\n"). &rset)) { /* new client connection */ clilen = sizeof(cliaddr). #endif for (i = 0. n). } if (--nready <= 0) break.sin_port)). MAXLINE)) == 0) { /*4connection closed by client */ close(sockfd). line.line[k]!='\0'. ntohs(cliaddr. /* add new descriptor to set */ if (connfd > maxfd) maxfd = connfd. i < FD_SETSIZE. (struct sockaddr *) &cliaddr. /* save descriptor */ break. rset = allset.

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

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

c $ mv a. $.0.out tcpservselect1 $ .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. $ cc tcpservselect01.Compiling and running server.1 13153 enter sentence to end enter #abcd# String : abcd sent to server --------------------------------------------------------------------------------------------------------------- ./tcpclient 127.

char line[MAXLINE].c #include <stdlib. servaddr.revents & POLLRDNORM) { /* new client connection */ clilen = sizeof(cliaddr).sin_family = AF_INET. /* -1 indicates available entry */ maxi = 0. INFTIM). 0). client[0]. . Design a TCP concurrent server to echo given set of sentences using poll functions tcpservpoll01. /* max index into client[] array */ /* end fig01 */ /* include fig02 */ for ( .h> #include <sys/stat. char **argv) { int k. client[0].h> #include <string. servaddr.h> #define MAXLINE 100 #define SERV_PORT 13154 #define POLLRDNORM 5 #define INFTIM 5 #define OPEN_MAX 5 int main(int argc. i.fd = -1. i < OPEN_MAX. socklen_t clilen. sizeof(servaddr)).h> #include <netinet/in.h> #include <stdio. maxi+1. struct pollfd client[OPEN_MAX]. int nready.events = POLLRDNORM. 5).h> #include <limits. ) { nready = poll(client.s_addr = htonl(INADDR_ANY). (struct sockaddr *) &servaddr.h> #include <arpa/inet.h> #include <sys/types. maxi. listenfd.h> /* for OPEN_MAX */ #include <poll.h> #include <sys/socket.Week8. connfd.h> #include <errno. sizeof(servaddr)). listenfd = socket(AF_INET. i++) client[i]. struct sockaddr_in cliaddr. listen(listenfd. if (client[0]. servaddr. servaddr. ssize_t n.sin_addr.sin_port = htons(SERV_PORT). sockfd.h> #include <fcntl. bind(listenfd. .fd = listenfd. SOCK_STREAM. bzero(&servaddr. for (i = 1.

" "). } if (i == OPEN_MAX) { printf("too many clients"). /* max index in client[] array */ if (--nready <= 0) continue.revents & (POLLRDNORM | POLLERR)) { if ( (n = read(sockfd. &clilen). printf(" length=%d data = %s\n". i). i < OPEN_MAX. #endif close(sockfd). line. } else{ printf("\n data from client is \n"). MAXLINE)) < 0) { if (errno == ECONNRESET) { /*4connection reset by client */ #ifdef NOTDEF printf("client[%d] aborted connection\n". #ifdef NOTDEF printf("new client: %s\n". } if (--nready <= 0) break.fd) < 0) continue.fd = connfd. } else if (n == 0) { /*4connection closed by client */ #ifdef NOTDEF printf("client[%d] closed connection\n". (struct sockaddr *) &cliaddr.fd = -1.fd = -1. i++) { /* check all clients for data */ if ( (sockfd = client[i]. /* save descriptor */ break. } client[i]. exit(0). /* no more readable descriptors */ } for (i = 1.line). #endif close(sockfd). n). #endif for (i = 1. /* no more readable descriptors . k. client[i].events = POLLRDNORM. i <= maxi. sock_ntop((struct sockaddr *) &cliaddr. i++) if (client[i]. if (client[i]. //write(sockfd. if (i > maxi) maxi = i. } else printf("readline error"). i).fd < 0) { client[i]. client[i]. strcpy(line.connfd = accept(listenfd. clilen)). line. k=strlen(line).

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

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

c $ mv a. $ cc tcpservpoll01.1 13153 enter sentence to end enter #aaaaaaaaaaaaaaaaaaaaaaaa# String : aaaaaaaaaaaaaaaaaaaaaaaa sent to server --------------------------------------------------------------------------------------------------------------- .out pollserv $ .0. $ cc democlient./client 127.0./pollserv data from client is data = aaaaaaaaaaaaaaaaaaaaaaaa Compiling and running Client.c $ mv a.out client $ ./ *************************************************************************** */ --------------------------------------------------------------------------------------------------------------c) Concurrent Server Application Using Poll. Compiling and running server.

n.cliaddr.h> #include <stdlib.c * DESCRIPTION:Contains Code for a echo server . SOCK_DGRAM. 0. char clientname[MAXNAME]. sizeof(cliaddr) ). memset(&cliaddr. 0 ).h> #include <sys/socket. using UDP * Invoke the Executable as a. . exit( 1 ).h> #include <errno. if( sd < 0 ) { perror( "socket" ). struct sockaddr_in serveraddress.h> #include <fcntl. sd = socket( AF_INET.h> #include <string.ret. char **V ) { int sd. sizeof(serveraddress) ).datareceived[BUFSIZE].c / *************************************************************************** *** * FILENAME : uechos.Week9.h> #include <sys/types. socklen_t length.h> #include <netinet/in.h> #include <signal. } memset(&serveraddress. 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> #define BUFSIZE 512 #define MYPORT 11710 #define MAXNAME 100 int main(int C.h> #include <arpa/inet.h> #include <sys/wait. udp_server. that will accept data * from a client process and sends that data back to client. 0.out * Copyright 2007 Aricent *************************************************************************** ***/ #include <stdio.

/*Sending the Received datagram back*/ datareceived[n]='\0'.(struct sockaddr*)&serveraddress.&length). n=recvfrom(sd.sin_addr.) { printf("I am waiting\n").s_addr = htonl(INADDR_ANY).h> #include <sys/socket.h> #include <signal.h> #include <errno.sin_addr. /*Received a datagram*/ length=sizeof(cliaddr).0.h> #include <stdlib.h> #include <arpa/inet.h> #include <fcntl.datareceived.h> #include <unistd.datareceived. 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 . sendto(sd.c / *************************************************************************** * FILENAME : uechoc.h> #define BUFSIZE 512 static void sig_usr(int).//IP ADDRESS ret=bind(sd.sizeof(serveraddress)). inet_ntop(AF_INET. printf("I have received %s\n".//PORT NO serveraddress.datareceived). if(ret<0) { perror("BIND FAILS").out ServerIP ServerPort * Copyright 2007 Aricent *************************************************************************** */ #include <stdio.c * DESCRIPTION:Contains Code for a echo client .h> #include <sys/types. . printf("Data Received from %s\n". } } --------------------------------------------------------------------------------------------------------------udp_client.(struct sockaddr *)&cliaddr.h> #include <netinet/in. } for(. (struct sockaddr*)&cliaddr .length). exit(1).BUFSIZE.serveraddress..&cliaddr.(UDP) * Invoke the Executable as a.n.0.sin_family = AF_INET.h> #include <string. serveraddress.sin_port = htons(MYPORT).sizeof(clientname))). clientname.

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

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

/ udp_server I am waiting Data Received from 127. UDP Client Server Application.c [user@localhost week9]$ mv a.out udp_client [user@localhost week9]$ .h /* . user@localhost week9]$ cc udp_client.0.1: abcd efgh Enter Data For the server 44 Week12 Design a RPC application to add and subtract a given pair of integers rpctime.0. rpctime. } = 2000001./ udp_client 127. } = 1./ **************************************************************************/ --------------------------------------------------------------------------------------------------------------5. [user@localhost week9]$ cc udp_server.1 11710 Client Starting service Enter Data For the server abcd efgh Data Sent To Server Data Received from server 127.x ***/ /*** ***/ /*** SPECIFICATION FILE FOR RPC TO DEFINE SERVER PROCEDURE AND ARGUMENTS ***/ / *************************************************************************** **/ program RPCTIME { version RPCTIMEVERSION { long GETTIME() = 1.0.x / *************************************************************************** **/ /*** rpctime.c [user@localhost week9]$ mv a.0. Compiling and running server.0.1 I have received abcd efgh rev is hgfe dcba I am waiting Compiling and running client.0.out udp_server [user@localhost week9]$ .

EXEMPLARY. extern long * gettime_1_svc(void *. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT. extern long * gettime_1_svc(). #else /* K&R C */ #define GETTIME 1 extern long * gettime_1(). INCLUDING. BUT NOT LIMITED TO. CLIENT *). PROCUREMENT OF SUBSTITUTE GOODS .* Please do not edit this file. BUT NOT LIMITED TO.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 *. OR CONSEQUENTIAL * DAMAGES (INCLUDING. struct svc_req *). extern int rpctime_1_freeresult ().c * * Copyright (c) 2000 Sean Walton and Macmillan Publishers. extern int rpctime_1_freeresult (SVCXPRT *. INDIRECT. #endif /* K&R C */ #ifdef __cplusplus } #endif #endif /* !_RPCTIME_H_RPCGEN */ --------------------------------------------------------------------------------------------------------------rpctime_client /* rpctime_client. * It was generated using rpcgen. xdrproc_t. caddr_t). INCIDENTAL. Use may be in * whole or in part in accordance to the General Public License (GPL). */ #ifndef _RPCTIME_H_RPCGEN #define _RPCTIME_H_RPCGEN #include <rpc/rpc. THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. SPECIAL.

char *gettime_1_arg. char *argv[]) . if (clnt == NULL) { clnt_pcreateerror (host). #endif /* DEBUG */ } int main (int argc. STRICT * LIABILITY. "call failed").c ***/ /*** ***/ / *************************************************************************** **/ /* * This is sample code generated by rpcgen. } #endif /* DEBUG */ result_1 = gettime_1((void*)&gettime_1_arg.h" void rpctime_1(char *host) { CLIENT *clnt. OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY. OR PROFITS. RPCTIMEVERSION. * These are only templates and you can use them * as a guideline for developing your own functions. EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. } else printf("%d |%s". WHETHER IN CONTRACT. DATA. clnt). LOSS OF USE. "udp"). RPCTIME. 47 long *result_1. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE. exit (1). ctime(result_1)).* OR SERVICES. #ifndef DEBUG clnt_destroy (clnt). #ifndef DEBUG clnt = clnt_create (host. *result_1. */ / *************************************************************************** **/ /*** rpctime_client. if (result_1 == (long *) NULL) { clnt_perror (clnt. */ #include "rpctime.

c /* rpctime_server.h" /* Default timeout can be changed using clnt_control() */ static struct timeval TIMEOUT = { 25.{ char *host. rpctime_1 (host). } return (&clnt_res). THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED.c * * Copyright (c) 2000 Sean Walton and Macmillan Publishers. (caddr_t) argp. 0. * It was generated using rpcgen. TIMEOUT) != RPC_SUCCESS) { return (NULL). GETTIME. exit (1). CLIENT *clnt) { static long clnt_res. sizeof(clnt_res)). } rpctime_cntl. argv[0]). if (argc < 2) { printf ("usage: %s server_host\n".c /* * Please do not edit this file. Use may be in * whole or in part in accordance to the General Public License (GPL). memset((char *)&clnt_res. } --------------------------------------------------------------------------------------------------------------rpctime_server. long * gettime_1(void *argp. exit (0). 0 }. */ #include <memory. (caddr_t) &clnt_res. (xdrproc_t) xdr_long. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES. INCLUDING. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE . BUT NOT LIMITED TO. if (clnt_call (clnt. } host = argv[1]. (xdrproc_t) xdr_void.h> /* for memset */ #include "rpctime.

h> . SPECIAL.c ***/ /*** ***/ / *************************************************************************** **/ /* * This is sample code generated by rpcgen.LIABLE * FOR ANY DIRECT. OR PROFITS. EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE.c /* * Please do not edit this file. OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY.h> #include <stdlib.h" #include <stdio. */ #include "rpctime. BUT NOT LIMITED TO.h" long * gettime_1_svc(void *argp. struct svc_req *rqstp) { static long result. DATA. * These are only templates and you can use them * as a guideline for developing your own functions. */ / *************************************************************************** **/ /*** rpctime_server. } --------------------------------------------------------------------------------------------------------------rpctime_svc. STRICT * LIABILITY. OR CONSEQUENTIAL * DAMAGES (INCLUDING.h> #include <string. * It was generated using rpcgen. return&result. WHETHER IN CONTRACT. */ #include "rpctime. PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES. LOSS OF USE.h> #include <rpc/pmap_clnt. EXEMPLARY. INCIDENTAL. OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE. INDIRECT. 50 time(&result).

return. (xdrproc_t) _xdr_argument. } Intmain (int argc. switch (rqstp->rq_proc) { case NULLPROC: (void) svc_sendreply (transp. } if (!svc_freeargs (transp. (caddr_t) &argument)) { fprintf (stderr. } memset ((char *)&argument. RPCTIMEVERSION).h> #ifndef SIG_PF #define SIG_PF void(*)(int) #endif static void rpctime_1(struct svc_req *rqstp. exit (1). char *(*local)(char *.h> #include <netinet/in. case GETTIME: _xdr_argument = (xdrproc_t) xdr_void. (char *)NULL).#include <memory. 0. (xdrproc_t) _xdr_result. (xdrproc_t) xdr_void. char *result. _xdr_result. _xdr_result = (xdrproc_t) xdr_long. "unable to free arguments"). default: svcerr_noproc (transp). local = (char *(*)(char *. } return. char **argv) { register SVCXPRT *transp. return. rqstp). (caddr_t) &argument)) { svcerr_decode (transp). if (result != NULL && !svc_sendreply(transp. } argument. sizeof (argument)). return. register SVCXPRT *transp) { union { int fill. xdrproc_t _xdr_argument. struct svc_req *). "%s". . result)) { svcerr_systemerr (transp). if (!svc_getargs (transp.h> #include <sys/socket. pmap_unset (RPCTIME. (xdrproc_t) _xdr_argument. struct svc_req *)) gettime_1_svc. } result = (*local)((char *)&argument. break.

0."). IPPROTO_TCP)) { fprintf (stderr.c files in the folder Step 2: $cc –c rpctime_client. exit(1)."). RPCTIMEVERSION./server & [1] 7610 $. RPCTIMEVERSION. rpctime_clnt.transp = svcudp_create(RPC_ANYSOCK). "%s". exit(1). if (transp == NULL) { fprintf (stderr.0. "unable to register (RPCTIME. 0).").o -lnsl Step 4: $cc –c rpctime_server.o rpctime_svc. RPCTIME. } if (!svc_register(transp.1 1277628700 |Sun Jun 27 14:21:40 2010 $. udp).c –o rpctime_clien. exit(1). fprintf (stderr./client 127. "%s". exit (1).0.")./client 127. 0.1 1277628718 |Sun Jun 27 14:21:58 2010 . "cannot create udp service. "unable to register (RPCTIME.o rpctime_clnt. } svc_run (). "%s". RPCTIME. "%s".0. rpctime_1.x. if (transp == NULL) { fprintf (stderr. /* NOTREACHED */ } --------------------------------------------------------------------------------------------------------------6. rpctime_1.o Step 5: $cc –o server rpctime_server.h. RPCTIMEVERSION. } if (!svc_register(transp.o -lnsl $. Step 1: $ rpcgen –C rpctime.c –o rpctime_server. RPCTIMEVERSION. IPPROTO_UDP)) { fprintf (stderr. rpctime_svc.c. "svc_run returned"). exit(1). } transp = svctcp_create(RPC_ANYSOCK. This creates rpctime. tcp).o Step 3: $cc –o client rpctime_client. RPC Application. "cannot create tcp service. "%s".

Sign up to vote on this title
UsefulNot useful