P. 1
Network Programming Lab Manual

Network Programming Lab Manual

|Views: 7|Likes:
Publicado porSiva Reddy

More info:

Published by: Siva Reddy on Aug 05, 2011
Direitos Autorais:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

08/22/2011

pdf

text

original

Sections

  • Week1
  • Week2
  • Week3
  • Week4
  • Week5
  • Week6
  • Week7
  • Week8
  • Week9
  • Week10
  • Week11
  • Week12

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

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

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

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

/fd_client hello 3. Run the client: % cc fd_client % mv a. Run the server: % cc fd_server. and the shell will return control to the command line.out fd_server %. 1. 4. 2.Execution Steps: b) Full Duplex.out fd_client %./fd_server & The server program will block here. The client program will send the string to server and block on the read to await the server's response. 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 .c % mv a.

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

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

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

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

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

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

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

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

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

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

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

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

out tcpserver [user@localhost week9]$ ./tcpserver Server:I am waiting-----Start of Main Loop Connection from 127.0. 1.0.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 tcpserver. [user@localhost week9]$ cc tcpclient.Execution Steps: 2.Compiling and running server.1 13153 enter sentence to end enter #Network Programming# String : Network Programming sent to server 23 ./tcpclient 127.0. Compiling and running client. TCP a) Client Server Application.0.c [user@localhost week9]$ mv a.out tcpclient [user@localhost week9]$.c [user@localhost week9]$ mv a.

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

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

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

fd.out IPAddress PortNo string * Copyright 2007 Aricent *****************************************************************************/ #include <stdio. char c.h> #include <arpa/inet. int i=0. sd = socket( AF_INET.h> #include <fcntl. exit(0). } if (V[2] == NULL ) { printf ("PL specify the server's Port No \n"). exit( 1 ). struct sockaddr_in serveraddress. } if (V[1] == NULL ) { printf ("PL specfiy the server's IP Address \n").h> #include <sys/types.h> #include <unistd.h> #include <sys/stat.c /*************************************************************************** * FILENAME : democlient.h> #include <errno.tcpclient. SOCK_STREAM.h> #include <netinet/in. char *V[] ) { int sd. 0 ). exit(0). } // if (V[3] == NULL ) { 27 .h> #include <sys/socket.h> #include <stdlib. if( sd < 0 ) { perror( "socket" ). char text[100]. * Invoke the Executable as a.h> #include <string. char *). int main( int C.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 .

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY. THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. INCLUDING. EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES. INDIRECT. OR CONSEQUENTIAL * DAMAGES (INCLUDING.c * * Copyright (c) 2000 Sean Walton and Macmillan Publishers.c /* rpctime_server. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES. STRICT * LIABILITY.h" long * gettime_1_svc(void *argp. DATA. */ #include "rpctime. INCIDENTAL. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT. SPECIAL. LOSS OF USE. * 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. Use may be in * whole or in part in accordance to the General Public License (GPL). */ /*****************************************************************************/ /*** rpctime_server.rpctime_server. struct svc_req *rqstp) { static long result. OR PROFITS. WHETHER IN CONTRACT. BUT NOT LIMITED TO. EXEMPLARY. BUT NOT LIMITED TO. 49 .c ***/ /*** ***/ /*****************************************************************************/ /* * This is sample code generated by rpcgen.

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

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

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

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

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

You're Reading a Free Preview

Descarregar
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->