NP Final Manual
NP Final Manual
NP Final Manual
Tech
Network Programming
Prepared By
R.Venkata Subbaiah BE.M.Tech.
Associate Professor IC RNEC@Development Cell
Department of CSE
RAO & NAIDU ENGINEERING COLLEGE
ONGOLE
Network Programming
Introduction to Inter process Communication : Pipes
Introduction: There are two types of pipes for two-way communication: anonymous pipes and named pipes. Anonymous pipes enable related processes to transfer information to each other. Typically, an anonymous pipe is used for redirecting the standard input or output of a child process so that it can exchange data with its parent process. To exchange data in both directions (duplex operation), you must create two anonymous pipes. The parent process writes data to one pipe using its write handle, while the child process reads the data from that pipe using its read handle. Similarly, the child process writes data to the other pipe and the parent process reads from it. Anonymous pipes cannot be used over a network, nor can they be used between unrelated processes. Properties of Pipe: 1) Pipes do not have a name. For this reason, the processes must share a parent process. This is the main drawback to pipes. However, pipes are treated as file descriptors, so the pipes remain open even after fork and exec. 2) Pipes do not distinguish between messages; they just read a fixed number of bytes. Newline (\n) can be used to separate messages. A structure with a length field can be used for message containing binary data. 3) Pipes can also be used to get the output of a command or to provide input to a command. Creation of Pipes Since A pipe provides a one-way flow of data. Int pipe (int * filedes); Int pipefd[2]; /* pipefd[0] is opened for reading;pipefd[1] is opened for writing */
I
o after call to fork
I
o after both calls to dup2
If the parent wants to receive data from the child, it should close fd1, and the child should close fd0. If the parent wants to send data to the child, it should close fd0, and the child should close fd1. Since descriptors are shared between the parent and child, we should always be sure to close the end of pipe we aren't concerned with. On a technical note, the EOF will never be returned if the unnecessary ends of the pipe are not explicitly closed.
WEEK 1: Aim: Implement the pipe using fork () /* file name pipe.c */ # include <stdio.h> # include <sys/types.h> # include <stdlib.h> # define MAXLINE 4096 int main() { int n,fd[2]; pid_t pid; char line[MAXLINE]; if(pipe(fd)<0) perror("pipe error.."); if((pid=fork())<0) perror("fork error..."); else if(pid>0) { close(fd[0]); write(fd[1],"Hello world\n",12); } else { close(fd[1]); n=read(fd[0],line,MAXLINE); write(1,line,n); } exit(0); } /* Compiling. $ cc pipe.c o pipe Execution.. $ pipe */ page: 5
Output: [student@localhost ~]$ vi pipe.c [student@localhost ~]$ cc pipe.c -o pipe [student@localhost ~]$ ./pipe Hello world
page: 6
Year : Semester:
2010
First
Aim: Implement the pipe using popen (), close () /* file name pipeopen.c */ # include <sys/wait.h> # include <stdio.h> # include <stdlib.h> # define MAXLINE 4096 # define PAGER "${PAGER:-more}" int main(int argc,char*argv[]) { char line[MAXLINE]; FILE *fpin,*fpout; if(argc!=2) { perror("\n usage :- a.out <path name>"); exit(0); } if((fpin=fopen(argv[1],"r"))==NULL) { printf("\nUnable to open %s",argv[1]); } if((fpout=popen(PAGER,"w"))==NULL) perror("popen error..."); while(fgets(line,MAXLINE,fpin)) { if(fputs(line,fpout)==EOF) perror("\n fput error..."); } if(ferror(fpin)) perror("fgets error..."); if(pclose(fpout)==-1) perror("pclose error.."); exit(0); }
page: 7
page: 8
Output: [student@localhost ~]$ vi pipeopen.c [student@localhost ~]$ cc pipeopen.c -o pipeopen [student@localhost ~]$ ./pipeopen myfile.txt This is the simple text in myfile To create a file: $cat > filename
page: 9
Year : Semester:
2010
First
Aim: Implement the FIFO form of IPC /* file name makefifo.c */ # include <stdio.h> # include <sys/types.h> # include <sys/stat.h> # include <fcntl.h> int main() { int fd; char buff[100]; /*creating FIFO */ if((mkfifo("./MyFifo",S_IFIFO|S_IRWXU|S_IRWXG|S_IRWXO))<0) perror("\nmkfifo error..."); /*creating reader process...*/ fd=open("./MyFifo",O_RDONLY|O_NONBLOCK); while(read(fd,buff,sizeof(buff))>0) printf("%s",buff); /*creating write process */ fd=open("./MyFifo",O_WRONLY); write(fd,"Hello world",12); close(fd); } /* Compiling. $ cc makefifo.c o makefifo Execution.. $ makefifo */
page: 10
Output: [student@localhost ~/khan]$ vi makefifo.c [student@localhost ~/khan]$ cc makefifo.c -o makefifo [student@localhost ~/khan]$ ./makefifo [student@localhost ~/khan]$ ./makefifo mkfifo error...: File exists
page: 11
Year : Semester:
2010
First
Aim: Implement file transfer using Message Queue form of IPC /* file msgsendQ.c */ # include <stdio.h> # include <string.h> # include <sys/stat.h> # include <sys/msg.h> # include <sys/ipc.h> # include <sys/types.h> struct message { long msg_type; char msg_data[1024]; }; int main(int arc,char*argv[]) { //message structure FILE*f; int x,y,i=0; char ch; int key=1234; int msg_id; struct message msg_obj1={100,"I"}; //function to put file to message Q if((f=fopen(argv[1],"r"))==NULL) perror("\nUnable to open file for reading..."); else { while((ch=getc(f))!=EOF) { msg_obj1.msg_data[i++]=ch; //writing to msg_data }
NP Lab Manual , RNEC
page: 12
fclose(f); //closing file } //creating msg q id if((msg_id=msgget(key,IPC_CREAT|0644))==-1) perror("\nUnable to get message id..."); else printf("\nmsgid=%d",msg_id); /*writing message to the q */ if((x=msgsnd(msg_id,&msg_obj1,strlen(msg_obj1.msg_data),IPC_NOWAIT)) ==-1) perror("\nUnable to send message..."); else printf("\nSend Msg Success : return %d",x); return 0; } /* Compiling. $CC msgsndQ.c -o msgsndQ Execution.. $msgsndQ <file name> */
page: 13
Output: [student@localhost ~]$ cc msgsndQ.c -o msgsndQ [student@localhost ~]$ ./msgsndQ pipe.c msgid=0 Send Msg Success : return 0[student@localhost ~]$
page: 14
Subject: NETWORK PROGRAMMING LAB Class : IV B-Tech C.S.E /* file msgrecvQ.c */ # include <stdio.h> # include <string.h> # include <sys/stat.h> # include <sys/msg.h> # include <sys/ipc.h> # include <sys/types.h> //message structure struct message { long msg_type; char msg_data[1024]; }; int main(int argc,char*argv[]) { FILE*f; int x,y,i=0; char ch; struct message msg_obj2={100,"M"}; int msg_id; //creating msg q id if((msg_id=msgget(1234,0644))==-1) perror("\nUnable to get message id..."); else printf("\nmsgid=%d",msg_id);
Year : Semester:
2010
First
/* rec message from q*/ if((y=msgrcv(msg_id,&msg_obj2,1024,100,MSG_NOERROR))==-1) perror(":- msgrcv error..."); else printf("\nRec Bytes : %d",y);
NP Lab Manual , RNEC
page: 15
if((f=fopen(argv[1],"w"))==NULL) perror("\nUnable to open file for writing..."); else { for(i=0;msg_obj2.msg_data[i]!=0;i++) { putc(msg_obj2.msg_data[i],f); } fclose(f); //closing file } return 0; } /* Compiling. $CC msgrecvQ.c -o msgrecvQ Execution.. $ msgrecvQ <new file name> */
page: 16
Output: [student@localhost ~]$ cc msgrecvQ.c -o msgrecvQ [student@localhost ~]$ ./msgrecv recvpipe.c msgid=0 Rec Bytes : 415[student@localhost ~]$ cat recvpipe.c /* file name pipe.c */ # include <stdio.h> # include <sys/types.h> # include <stdlib.h> # define MAXLINE 4096 int main() { int n,fd[2]; pid_t pid; char line[MAXLINE]; if(pipe(fd)<0) perror("pipe error.."); if((pid=fork())<0) perror("fork error..."); else if(pid>0) { close(fd[0]); write(fd[1],"hello world\n",12); } else { close(fd[1]); n=read(fd[0],line,MAXLINE); write(1,line,n); } exit(0); }
page: 17
Year : Semester:
2010
First
Aim: Write a program to create an integer variable using shared memory concept and increment the variable simultaniously two processes. Use semaphores to avoid race conditions. /*file name sem.c */ #include <unistd.h> #include <errno.h> #include <sys/stat.h> #include <string.h> #include <sys/types.h> #include <fcntl.h> #include <sys/types.h> #include <sys/ipc.h> #include <sys/shm.h> #include <stdio.h> #include <sys/sem.h> # include <stdlib.h> #define SHMSZ 4 /* Good for integer */ #define BUF_SZ 16 #define SHM_KEY 1234 #define SEM_KEY 1235 #define CHILD_INCREMENT_COUNT 67787 #define PARENT_INCREMENT_COUNT 84823 union semun { int val; /* value for SETVAL */ struct semid_ds *buf; /* buffer for IPC_STAT, IPC_SET */ unsigned short *array; /* array for GETALL, SETALL */ /* Linux specific part: */ struct seminfo *__buf; /* buffer for IPC_INFO */ };
page: 18
main() { int shmid; int semid; key_t key; int *child_shm, *parent_shm; union semun arg; int i; struct sembuf operations[1]; int status; int pid; /* Create the shared segment.& semaphore. */ if ((shmid = shmget(SHM_KEY, SHMSZ, IPC_CREAT | 0666)) < 0) { perror("shmget"); exit(1); } if ((semid = semget(SEM_KEY, 1, IPC_CREAT | 0666)) < 0) { perror("semget"); exit(1); } /* * Initialize the semaphore to value 1. The idea is multiple processes * do semop() of -1. So only one is allowed in critical section. * initialize the shm to 0. */ arg.val = 1; if (semctl(semid, 0, SETVAL, arg) < 0) { perror("semctl"); exit(1); }
page: 19
if ((parent_shm = shmat(shmid, NULL, 0)) == (int *)-1) { perror("parent shmat"); exit(1); } *parent_shm = 0; /* * create a child process. The above opened shm & sem fds get * copied to child process as a result of fork(). They both attach to the * shared memory and use the semphore to increment the value in the shm. */ if ((pid = fork()) < 0) { printf("Child Process Creation Error:%d\n", errno); return; } /* * Child process attaches to shm. It fill operations to block till * it gets -1. Since the initial value of semaphore is 1, only one * process can do -1. The other process will see the value as 0 and * block till it sees sem value as 1. After semop(), increment the shm * integer by 1. Then again use the semop to set the sem value to 1, so * that other process gets the chance to run. * Repeat the above for a defined number of times. Later similar thing is * done for parent process also. */ if (pid == 0) { if ((child_shm = shmat(shmid, NULL, 0)) == (int *)-1) { perror("child shmat"); exit(1); }
page: 20
for (i = 0; i < CHILD_INCREMENT_COUNT; i++) { operations[0].sem_num = 0; operations[0].sem_op = -1; operations[0].sem_flg = 0; if (semop(semid, operations, 1) < 0) { perror("child semop"); exit(1); } *child_shm = *child_shm + 1; if (i%1000 == 0) { usleep(1); // sleep 1 us to increase window of critical section } operations[0].sem_num = 0; operations[0].sem_op = 1; operations[0].sem_flg = 0; if (semop(semid, operations, 1) < 0) { perror("child semop"); exit(1); } } } if (pid != 0) { for (i = 0; i < PARENT_INCREMENT_COUNT; i++) { operations[0].sem_num = 0; operations[0].sem_op = -1; operations[0].sem_flg = 0;
NP Lab Manual , RNEC
page: 21
if (semop(semid, operations, 1) < 0) { perror("parent semop"); exit(1); } *parent_shm = *parent_shm + 1; if (i%1500 == 0) { usleep(1); // sleep 1 us to increase window of critical section } operations[0].sem_num = 0; operations[0].sem_op = 1; operations[0].sem_flg = 0; if (semop(semid, operations, 1) < 0) { perror("parent semop"); exit(1); } } // wait for child to complete wait(&status); /* * now that parent and child are done incrementing, check the * consistency of the shm memory. */ printf("Child Incremented %d times, Parent %d times. SHM Value %d \n",CHILD_INCREMENT_COUNT,PARENT_INCREMENT_COUNT, *parent_shm);
page: 22
if (*parent_shm == (CHILD_INCREMENT_COUNT + PARENT_INCREMENT_COUNT)) { printf("Total of Parent & Child matches SHM value\n"); } else { printf("BUG - Total of Parent & Child DOESNT match SHM value\n"); } } exit(0); } /* Compiling. $CC sem.c -o sema Execution.. $ sema */
page: 23
Output: [student@localhost ~]$ cc sem.c -o sema [student@localhost ~]$ ./sema Child Incremented 67787 times, Parent 84823 times. SHM Value 152610 Total of Parent & Child matches SHM value
page: 24
Year : Semester:
2010
First
AIM: Design TCP iterative Client and server application to reverse the given input sentence /*tcp_strrev_ser.c*/
#include "unp.h" void str_echo(int sockfd) { long arg1, arg2; int x,y; ssize_t n; char line[MAXLINE]; char swp; for ( ; ; ) { if ( (n = Readline(sockfd, line, MAXLINE)) == 0) return;/* connection closed by other end */ n = strlen(line); /*strrev(line);*/ for(x=0,y=n-1;x<n/2;x++,y--) { swp=line[x]; line[x]=line[y]; line[y]=swp; } printf("\nReq From Client : %s",line); Writen(sockfd, line, n); } } int main(int argc, char **argv) { int listenfd, connfd; pid_t childpid;
NP Lab Manual , RNEC
page: 25
socklen_t clilen; struct sockaddr_in cliaddr, servaddr; listenfd = Socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(SERV_PORT); Bind(listenfd, (SA *) &servaddr, sizeof(servaddr)); Listen(listenfd, LISTENQ); printf("Server Running on Port %d\n", SERV_PORT); for ( ; ; ) { clilen = sizeof(cliaddr); connfd = Accept(listenfd, (SA *) &cliaddr, &clilen); if ( (childpid = Fork()) == 0) { /* child process */ Close(listenfd); /* close listening socket */ str_echo(connfd); /* process the request */ exit(0); } Close(connfd); /* parent closes connected socket */ } } /* Compiling. $CC tcp_strrev_ser.c wrapsock.c -o tcp_strrev_ser Execution.. $tcp_strrev_ser */
page: 26
Output: [student@localhost ~]$ cc tcp_strrev_ser.c wrapsock.c -o tcp_strrev_ser [student@localhost ~]$ ./ tcp_strrev_ser Server Running on Port 9877 Req From Client : iah Req From Client : eyb Req From Client : Suspended
page: 27
Subject: NETWORK PROGRAMMING LAB Class : IV B-Tech C.S.E /* tcp_strrev_clnt.c */ #include "unp.h"
Year : Semester:
2010
First
void str_cli(FILE *fp, int sockfd) { char sendline[MAXLINE], recvline[MAXLINE]; while (Fgets(sendline, MAXLINE, fp) != NULL) { Writen(sockfd, sendline, strlen(sendline)); if (Readline(sockfd, recvline, MAXLINE) == 0) err_quit("str_cli: server terminated prematurely"); Fputs(recvline, stdout); } } int main(int argc, char **argv) { int sockfd; struct sockaddr_in servaddr; if (argc != 2) err_quit("usage: tcpcli <IPaddress>"); sockfd = Socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(SERV_PORT); Inet_pton(AF_INET, argv[1], &servaddr.sin_addr); Connect(sockfd, (SA *) &servaddr, sizeof(servaddr)); str_cli(stdin, sockfd); /* do it all */ exit(0); } /* Compiling. $CC tcp_strrev_clnt.c wrapsock.c -o tcp_strrev_clnt Execution.. $tcp_strrev_clnt <IP Address> */
NP Lab Manual , RNEC
page: 28
Output: [student@localhost ~]$ ./ tcp_strrev_clnt.c wrapsock.c o tcp_strrev_clnt [student@localhost ~]$ ./ tcp_strrev_clnt 169.254.17.41 hai bye
page: 29
Year : Semester:
2010
First
AIM: Design TCP client and server application to transfer file /* tcp_fil_ser.c */ #include "unp.h"
void str_echo(int sockfd) { long arg1, arg2; ssize_t n; char line[MAXLINE]; char fname[100]; char ch; FILE*f; int i=0; for ( ; ; ) { if ( (n = Readline(sockfd, line, MAXLINE)) == 0) return; /* connection closed by other end */ n = strlen(line); printf("\nReq From Client for file : %s",line); printf("\n.......%s",fname); f=fopen(myfile,"r"); while((ch=getc(f))!=EOF) { line[i++]=ch; } line[i]=0; n=i; fclose(f); Writen(sockfd, line, n); } } int main(int argc, char **argv) { int listenfd, connfd; pid_t childpid; socklen_t clilen; struct sockaddr_in cliaddr, servaddr; listenfd = Socket(AF_INET, SOCK_STREAM, 0);
NP Lab Manual , RNEC
page: 30
bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(SERV_PORT); Bind(listenfd, (SA *) &servaddr, sizeof(servaddr)); Listen(listenfd, LISTENQ); printf("Server Running on Port %d\n", SERV_PORT); for ( ; ; ) { clilen = sizeof(cliaddr); connfd = Accept(listenfd, (SA *) &cliaddr, &clilen); if ( (childpid = Fork()) == 0) { /* child process */ Close(listenfd); /* close listening socket */ str_echo(connfd); /* process the request */ exit(0); } Close(connfd); /* parent closes connected socket */ } } /* Compiling. $CC tcp_file_ser.c wrapsock.c -o tcpfileser Execution.. $ tcpfileser */
page: 31
Output: [student@localhost ~]$ ./ tcp_file_ser.c wrapsock.c o tcpfileser [student@localhost ~]$ ./ tcpfileser Server Running on Port 9877
page: 32
Subject: NETWORK PROGRAMMING LAB Class : IV B-Tech C.S.E /* tcp_file_clnt.c*/ #include "unp.h"
Year : Semester:
2010
First
void str_cli(FILE *fp, int sockfd) { char sendline[MAXLINE], recvline[MAXLINE]; while (Fgets(sendline, MAXLINE, fp) != NULL) { Writen(sockfd, sendline, strlen(sendline)); if (Readline(sockfd, recvline, MAXLINE) == 0) err_quit("str_cli: server terminated prematurely"); Fputs(recvline, stdout); } } int main(int argc, char **argv) { int sockfd; struct sockaddr_in servaddr; if (argc != 2) err_quit("usage: tcpcli <IPaddress>"); sockfd = Socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(SERV_PORT); Inet_pton(AF_INET, argv[1], &servaddr.sin_addr); Connect(sockfd, (SA *) &servaddr, sizeof(servaddr)); str_cli(stdin, sockfd); /* do it all */ exit(0); } /* Compiling. $CC tcp_file_clnt.c wrapsock.c -o tcpfileclnt Execution.. $ tcpfileclnt <IP Address> */
NP Lab Manual , RNEC
page: 33
Output: [student@localhost ~]$ ./ tcp_file_clnt.c wrapsock.c o tcpfileclnt [student@localhost ~]$ ./ tcpfileclnt 127.0.0.1 Hai printing from myfile
page: 34
Year : Semester:
2010
First
AIM: Design a TCP concurrent server to echo given text into upper case using multiplexing system call select /* tcp_str_ser.c */ #include "unp.h" void str_echo(int sockfd) { long arg1, arg2; ssize_t n; char line[MAXLINE]; for ( ; ; ) { if ( (n = Readline(sockfd, line, MAXLINE)) == 0) return; /* connection closed by other end */ n = strlen(line); printf("\nReq From Client : %s",line); /* converting into upper case */ for(i=0;i<n;i++) { if(line[i]>=97 && line[i]<=122) { line[i]-=32; } } line[i]=0; /* null */ Writen(sockfd, line, n); } } int main(int argc, char **argv) { int listenfd, connfd; pid_t childpid; socklen_t clilen; struct sockaddr_in cliaddr, servaddr; listenfd = Socket(AF_INET, SOCK_STREAM, 0);
NP Lab Manual , RNEC
page: 35
bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_addr.s_addr = htonl(INADDR_ANY); servaddr.sin_port = htons(SERV_PORT); Bind(listenfd, (SA *) &servaddr, sizeof(servaddr)); Listen(listenfd, LISTENQ); printf("Server Running on Port %d\n", SERV_PORT); for ( ; ; ) { clilen = sizeof(cliaddr); connfd = Accept(listenfd, (SA *) &cliaddr, &clilen); if ( (childpid = Fork()) == 0) { /* child process */ Close(listenfd); /* close listening socket */ str_echo(connfd); /* process the request */ exit(0); } Close(connfd); /* parent closes connected socket */ } } /* Compiling. $CC tcp_str_ser.c wrapsock.c -o tcpstrser Execution.. $ tcpstrser */
page: 36
Output: [student@localhost ~]$ cc tcpstrser.c wrapsock.c -o tcpstrser [student@localhost ~]$ ./tcpstrser Server Running on Port 9877 Req From Client : khan Req From Client : ram Req From Client : karthik
page: 37
Subject: NETWORK PROGRAMMING LAB Class : IV B-Tech C.S.E /* tcp_strrev_clnt.c */ #include "unp.h"
Year : Semester:
2010
First
void str_cli(FILE *fp, int sockfd) { char sendline[MAXLINE], recvline[MAXLINE]; while (Fgets(sendline, MAXLINE, fp) != NULL) { Writen(sockfd, sendline, strlen(sendline)); if (Readline(sockfd, recvline, MAXLINE) == 0) err_quit("str_cli: server terminated prematurely"); Fputs(recvline, stdout); } } int main(int argc, char **argv) { int sockfd; struct sockaddr_in servaddr; if (argc != 2) err_quit("usage: tcpcli <IPaddress>"); sockfd = Socket(AF_INET, SOCK_STREAM, 0); bzero(&servaddr, sizeof(servaddr)); servaddr.sin_family = AF_INET; servaddr.sin_port = htons(SERV_PORT); Inet_pton(AF_INET, argv[1], &servaddr.sin_addr); Connect(sockfd, (SA *) &servaddr, sizeof(servaddr)); str_cli(stdin, sockfd); /* do it all */ exit(0); } /* Compiling. $CC tcp_str_clnt.c wrapsock.c -o tcpstrclnt Execution.. $ tcpstrclnt <IP Address> */
NP Lab Manual , RNEC
page: 38
Output: [student@localhost ~]$ cc tcpstrclnt.c wrapsock.c -o tcpstrclnt [student@localhost ~]$ ./tcpstrclnt 169.254.17.41 khan KHAN ram RAM karthik KARTHIK
page: 39
Year : Semester:
2010
First
Aim: Design UDP client and server application to reverse the given input sentence /* udp_strrev_ser.c */ /* UDP echo client/server with select() (timeout option). See udpClient.c */ #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdio.h> #include <unistd.h> /* close() */ #include <string.h> /* memset() */ #define LOCAL_SERVER_PORT 1500 #define MAX_MSG 100 int main(int argc, char *argv[]) { int l,x,y; char swp; int sd, rc, n, cliLen, flags; struct sockaddr_in cliAddr, servAddr; char msg[MAX_MSG]; /* socket creation */ sd=socket(AF_INET, SOCK_DGRAM, 0); if(sd<0) { printf("%s: cannot open socket \n",argv[0]); exit(1); } /* bind local server port */ servAddr.sin_family = AF_INET;
NP Lab Manual , RNEC
page: 40
servAddr.sin_addr.s_addr = htonl(INADDR_ANY); servAddr.sin_port = htons(LOCAL_SERVER_PORT); rc = bind (sd, (struct sockaddr *) &servAddr,sizeof(servAddr)); if(rc<0) { printf("%s: cannot bind port number %d \n", argv[0], LOCAL_SERVER_PORT); exit(1); } printf("%s: waiting for data on port UDP %u\n", argv[0],LOCAL_SERVER_PORT); flags = 0; /* server infinite loop */ while(1) { /* init buffer */ memset(msg,0x0,MAX_MSG); /* receive message */ cliLen = sizeof(cliAddr); n = recvfrom(sd, msg, MAX_MSG, flags,(struct sockaddr *)&cliAddr,&cliLen); if(n<0) { printf("%s: cannot receive data \n",argv[0]); continue; } /*reversing string */ l=strlen(msg); for(x=0,y=l-1;x<l/2;x++,y--) { swp=msg[x]; msg[x]=msg[y]; msg[y]=swp; } /* print received message */ printf("%s: from %s:UDP%u : %s \n",
NP Lab Manual , RNEC
page: 41
argv[0],inet_ntoa(cliAddr.sin_addr), ntohs(cliAddr.sin_port),msg); sleep(1); sendto(sd,msg,n,flags,(struct sockaddr *)&cliAddr,cliLen); }/* end of server infinite loop */ return 0; } /* Compiling. $CC udp_strrev_ser.c wrapsock.c -o udpstrrevser Execution.. $udpstrrevser */
page: 42
Output: [student@localhost ~]$ cc udp_strrev_ser.c wrapsock.c -o udpstrrrevser [student@localhost ~]$ ./udpstrrevser ./ udpstrrevser: waiting for data on port UDP 1500 ./ udpstrrevser: from 169.254.17.41:UDP32782 : iah ./ udpstrrevser: from 169.254.17.41:UDP32782 : woh ./ udpstrrevser: from 169.254.17.41:UDP32782 : era ./ udpstrrevser: from 169.254.17.41:UDP32782 : u
page: 43
Subject: NETWORK PROGRAMMING LAB Class : IV B-Tech C.S.E /*udp_strrev_clnt.c */ #include <stdlib.h> /* for exit() */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdio.h> #include <unistd.h> #include <string.h> /* memset() */ #include <sys/time.h> /* select() */
Year : Semester:
2010
First
#define REMOTE_SERVER_PORT 1500 #define MAX_MSG 100 #define SOCKET_ERROR -1 int isReadable(int sd,int * error,int timeOut) { // milliseconds fd_set socketReadSet; FD_ZERO(&socketReadSet); FD_SET(sd,&socketReadSet); struct timeval tv; if (timeOut) { tv.tv_sec = timeOut / 1000; tv.tv_usec = (timeOut % 1000) * 1000; } else { tv.tv_sec = 0; tv.tv_usec = 0; } // if if (select(sd+1,&socketReadSet,0,0,&tv) == SOCKET_ERROR) { *error = 1; return 0; } // if
NP Lab Manual , RNEC
page: 44
*error = 0; return FD_ISSET(sd,&socketReadSet) != 0; } /* isReadable */ int main(int argc, char *argv[]) { int sd, rc, i, n, echoLen, flags, error, timeOut; struct sockaddr_in cliAddr, remoteServAddr, echoServAddr; struct hostent *h; char msg[MAX_MSG]; /* check command line args */ if(argc<3) { printf("usage : %s <server> <data1> ... <dataN> \n", argv[0]); exit(1); } /* get server IP address (no check if input is IP address or DNS name */ h = gethostbyname(argv[1]); if(h==NULL) { printf("%s: unknown host '%s' \n", argv[0], argv[1]); exit(1); } printf("%s: sending data to '%s' (IP : %s) \n", argv[0], h->h_name, inet_ntoa(*(struct in_addr *)h->h_addr_list[0])); remoteServAddr.sin_family = h->h_addrtype; memcpy((char *) &remoteServAddr.sin_addr.s_addr,h->h_addr_list[0], h>h_length); remoteServAddr.sin_port = htons(REMOTE_SERVER_PORT); /* socket creation */ sd = socket(AF_INET,SOCK_DGRAM,0); if(sd<0) { printf("%s: cannot open socket \n",argv[0]); exit(1); }
NP Lab Manual , RNEC
page: 45
/* bind any port */ cliAddr.sin_family = AF_INET; cliAddr.sin_addr.s_addr = htonl(INADDR_ANY); cliAddr.sin_port = htons(0); rc = bind(sd, (struct sockaddr *) &cliAddr, sizeof(cliAddr)); if(rc<0) { printf("%s: cannot bind port\n", argv[0]); exit(1); } flags = 0; timeOut = 100; // ms /* send data */ for(i=2;i<argc;i++) { rc = sendto(sd, argv[i], strlen(argv[i])+1, flags, (struct sockaddr *) &remoteServAddr,sizeof(remoteServAddr)); if(rc<0) { printf("%s: cannot send data %d \n",argv[0],i-1); close(sd); exit(1); } /* BEGIN jcs 3/30/05 */ /* init buffer */ memset(msg,0x0,MAX_MSG); while (!isReadable(sd,&error,timeOut)) printf("."); printf("\n"); /* receive echoed message */ echoLen = sizeof(echoServAddr); n = recvfrom(sd, msg, MAX_MSG, flags,(struct sockaddr *) &echoServAddr,&echoLen);
page: 46
if(n<0) { printf("%s: cannot receive data \n",argv[0]); continue; } /* print received message */ printf("%s: echo from %s:UDP%u : %s \n",argv[0],inet_ntoa(echoServAddr.sin_addr),ntohs(echoServAddr.sin_port),m sg); } return 1; } /* Compiling. $ cc udp_strrev_clnt.c wrapsock.c -o udpstrrevclnt Execution.. $ udpstrrevclnt <IP Address> data */
page: 47
Output: [student@localhost ~]$ cc udp_strrev_clnt.c wrapsock.c -o udpstrrevclnt [student@localhost ~]$ ./ udpstrrevclnt 169.254.17.41 hai how are u ./ udpstrrevclnt: sending data to '169.254.17.41' (IP : 169.254.17.41) .......... ./ udpstrrevclnt: echo from 169.254.17.41:UDP1500 : iah .......... ./ udpstrrevclnt: echo from 169.254.17.41:UDP1500 : woh .......... ./ udpstrrevclnt: echo from 169.254.17.41:UDP1500 : era .......... ./udpstrrevclnt: echo from 169.254.17.41:UDP1500 : u
page: 48
Subject: NETWORK PROGRAMMING LAB Class : IV B-Tech C.S.E WEEK 9: Aim: Design UDP client server to transfer a file /* server program */ /* udp_file_ser.c */ #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdio.h> #include <unistd.h> /* close() */ #include <string.h> /* memset() */ #define LOCAL_SERVER_PORT 1500 #define MAX_MSG 3000 int main(int argc, char *argv[]) { FILE*f; int i=0; char fname[100],ch; int sd, rc, n, cliLen, flags; struct sockaddr_in cliAddr, servAddr; char msg[MAX_MSG]; /* socket creation */ sd=socket(AF_INET, SOCK_DGRAM, 0); if(sd<0) { printf("%s: cannot open socket \n",argv[0]); exit(1); } /* bind local server port */ servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = htonl(INADDR_ANY); servAddr.sin_port = htons(LOCAL_SERVER_PORT);
NP Lab Manual , RNEC
Year : Semester:
2010
First
page: 49
rc = bind (sd, (struct sockaddr *) &servAddr,sizeof(servAddr)); if(rc<0) { printf("%s: cannot bind port number %d \n", argv[0], LOCAL_SERVER_PORT); exit(1); } printf("%s: waiting for data on port UDP %u\n", argv[0],LOCAL_SERVER_PORT); flags = 0; /* server infinite loop */ while(1) { /* init buffer */ memset(msg,0x0,MAX_MSG); /* receive message */ cliLen = sizeof(cliAddr); n = recvfrom(sd, msg, MAX_MSG, flags,(struct sockaddr *) &cliAddr, &cliLen); if(n<0) { printf("%s: cannot receive data \n",argv[0]); continue; } /*reading file contents */ strcpy(fname,msg); if((f=fopen(fname,"r"))==NULL) perror("\nFile not found..."); i=0; //reading data to msg while((ch=getc(f))!=EOF) { msg[i++]=ch; } msg[i]='\0'; n=i; fclose(f); //closing stream /* print received message */
NP Lab Manual , RNEC
page: 50
printf("%s: from %s:UDP%u : %s \n" , argv[0], inet_ntoa(cliAddr.sin_addr), ntohs(cliAddr.sin_port),msg); sleep(1); sendto(sd,msg,n,flags,(struct sockaddr *)&cliAddr,cliLen); }/* end of server infinite loop */ return 0; } /* Compiling. $ cc udp_file_ser.c wrapsock.c -o udp_file_ser Execution.. $ udp_file_ser */
page: 51
Output: [student@localhost ~]$ cc udp_file_ser.c wrapsock.c -o udp_file_ser [student@localhost ~]$ ./ udp_file_ser ./udptranser: waiting for data on port UDP 1500 ./ udp_file_ser: from 169.254.17.41:UDP32782 : #include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<fcntl.h> #define MAXLINE 4096 int main(int argc,char*argv[]) { int fd,n; char buff[2000]; if(argc=2) { printf("\n wrong arg..."); exit(0); } if((fd=open(argv[1],O_RDONLY))<0) { printf("\n unable to open file%s",argv[1]); exit(0); } else printf("\n %s file is opened",argv[1]); while((n=read(fd,buff,MAXLINE))>0) { write(1,buff,n); } exit(0); }
page: 52
Subject: NETWORK PROGRAMMING LAB Class : IV B-Tech C.S.E /* udp_file_clnt.c */ #include <stdlib.h> /* for exit() */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdio.h> #include <unistd.h> #include <string.h> /* memset() */ #include <sys/time.h> /* select() */ #define REMOTE_SERVER_PORT 1500 #define MAX_MSG 3000 #define SOCKET_ERROR -1
Year : Semester:
2010
First
int isReadable(int sd,int * error,int timeOut) { // milliseconds fd_set socketReadSet; FD_ZERO(&socketReadSet); FD_SET(sd,&socketReadSet); struct timeval tv; if (timeOut) { tv.tv_sec = timeOut / 1000; tv.tv_usec = (timeOut % 1000) * 1000; } else { tv.tv_sec = 0; tv.tv_usec = 0; } // if if (select(sd+1,&socketReadSet,0,0,&tv) == SOCKET_ERROR) { *error = 1; return 0; } // if
NP Lab Manual , RNEC
page: 53
*error = 0; return FD_ISSET(sd,&socketReadSet) != 0; } /* isReadable */ /* END jcs 3/30/05 */ int main(int argc, char *argv[]) { int sd, rc, i, n, echoLen, flags, error, timeOut; struct sockaddr_in cliAddr, remoteServAddr, echoServAddr; struct hostent *h; char msg[MAX_MSG]; /* check command line args */ if(argc<3) { printf("usage : %s <server> <data1> ... <dataN> \n", argv[0]); exit(1); } /* get server IP address (no check if input is IP address or DNS name */ h = gethostbyname(argv[1]); if(h==NULL) { printf("%s: unknown host '%s' \n", argv[0], argv[1]); exit(1); } printf("%s: sending data to '%s' (IP : %s) \n", argv[0], h->h_name, inet_ntoa(*(struct in_addr *)h->h_addr_list[0])); remoteServAddr.sin_family = h->h_addrtype; memcpy((char *) &remoteServAddr.sin_addr.s_addr,h->h_addr_list[0], h->h_length); remoteServAddr.sin_port = htons(REMOTE_SERVER_PORT); /* socket creation */ sd = socket(AF_INET,SOCK_DGRAM,0); if(sd<0) { printf("%s: cannot open socket \n",argv[0]); exit(1); } /* bind any port */
NP Lab Manual , RNEC
page: 54
cliAddr.sin_family = AF_INET; cliAddr.sin_addr.s_addr = htonl(INADDR_ANY); cliAddr.sin_port = htons(0); rc = bind(sd, (struct sockaddr *) &cliAddr, sizeof(cliAddr)); if(rc<0) { printf("%s: cannot bind port\n", argv[0]); exit(1); } flags = 0; timeOut = 100; // ms /* send data */ for(i=2;i<argc;i++) { rc = sendto(sd, argv[i], strlen(argv[i])+1, flags, (struct sockaddr *) &remoteServAddr, sizeof(remoteServAddr)); if(rc<0) { printf("%s: cannot send data %d \n",argv[0],i-1); close(sd); exit(1); } /* init buffer */ memset(msg,0x0,MAX_MSG); while (!isReadable(sd,&error,timeOut)) printf("."); printf("\n"); /* receive echoed message */ echoLen = sizeof(echoServAddr); n = recvfrom(sd, msg, MAX_MSG, flags,(struct sockaddr *) &echoServAddr, &echoLen); if(n<0) { printf("%s: cannot receive data \n",argv[0]); continue; }
NP Lab Manual , RNEC
page: 55
/* print received message */ printf("%s: echo from %s:UDP%u : %s \n",argv[0],inet_ntoa(echoServAddr.sin_addr),ntohs(echoServAddr.sin_port),m sg); } return 1; } /* Compiling. $CC cc udp_file_clnt.c wrapsock.c -o udp_file_clnt Execution.. $ udp_file_clnt <IP Address> <File Name> */
page: 56
Output: [student@localhost ~]$ cc udp_file_clnt.c wrapsock.c -o udp_file_clnt [student@localhost ~]$ ./ udp_file_clnt 169.254.17.41 io.c ./ udp_file_clnt i: sending data to '169.254.17.41' (IP : 169.254.17.41) .......... ./ udp_file_clnt: echo from 169.254.17.41:UDP1500 : #include<stdio.h> #include<stdlib.h> #include<sys/types.h> #include<fcntl.h> #define MAXLINE 4096 int main(int argc,char*argv[]) { int fd,n; char buff[2000]; if(argc=2) { printf("\n wrong arg..."); exit(0); } if((fd=open(argv[1],O_RDONLY))<0) { printf("\n unable to open file%s",argv[1]); exit(0); } else printf("\n %s file is opened",argv[1]); while((n=read(fd,buff,MAXLINE))>0) { write(1,buff,n); } exit(0); }
page: 57
Year : Semester:
2010
First
AIM: Design a UDP poll client server application to multiplex TCP and UDP requests for converting a given text in to upper case /* tcp_str_ser.c */ #include <stdlib.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdio.h> #include <unistd.h> /* close() */ #include <string.h> /* memset() */ #define LOCAL_SERVER_PORT 1500 #define MAX_MSG 100 int main(int argc, char *argv[]) { int sd, rc, n, cliLen, flags,x,l; struct sockaddr_in cliAddr, servAddr; char msg[MAX_MSG]; /* socket creation */ sd=socket(AF_INET, SOCK_DGRAM, 0); if(sd<0) { printf("%s: cannot open socket \n",argv[0]); exit(1); } /* bind local server port */ servAddr.sin_family = AF_INET; servAddr.sin_addr.s_addr = htonl(INADDR_ANY); servAddr.sin_port = htons(LOCAL_SERVER_PORT); rc = bind (sd, (struct sockaddr *) &servAddr,sizeof(servAddr));
NP Lab Manual , RNEC
page: 58
if(rc<0) { printf("%s: cannot bind port number %d \n", argv[0], LOCAL_SERVER_PORT); exit(1); } printf("%s: waiting for data on port UDP %u\n", argv[0],LOCAL_SERVER_PORT); /* BEGIN jcs 3/30/05 */ flags = 0; /* END jcs 3/30/05 */ /* server infinite loop */ while(1) { /* init buffer */ memset(msg,0x0,MAX_MSG); /* receive message */ cliLen = sizeof(cliAddr); n = recvfrom(sd, msg, MAX_MSG, flags, (struct sockaddr *) &cliAddr, &cliLen); if(n<0) { printf("%s: cannot receive data \n",argv[0]); continue; } l=strlen(msg); for(x=0;x<l;x++) { if(msg[x]>=97&&msg[x]<=122) { msg[x]-=32; } } /* print received message */ printf("%s: from %s:UDP%u : %s \n", argv[0],inet_ntoa(cliAddr.sin_addr), ntohs(cliAddr.sin_port),msg); /* BEGIN jcs 3/30/05 */
NP Lab Manual , RNEC
page: 59
sleep(1); sendto(sd,msg,n,flags,(struct sockaddr *)&cliAddr,cliLen); /* END jcs 3/30/05 */ } /* end of server infinite loop */ return 0; } /* Compiling. $CC udp_str_ser.c wrapsock.c -o udpstrser Execution.. $udpstrser */
page: 60
Output: [student@localhost ~]$ cc udp_str_ser.c wrapsock.c -o udpstrser [student@localhost ~]$./udpstrser udpstrser : waiting for data on port UDP 1500 udpstrser : from 127.0.0.1 : UDP32768: HAI udpstrser : from 127.0.0.1 : UDP32768: HOW udpstrser : from 127.0.0.1 : UDP32768: ARE udpstrser : from 127.0.0.1 : UDP32768: YOU
page: 61
Subject: NETWORK PROGRAMMING LAB Class : IV B-Tech C.S.E /*udp_str_clnt.c*/ #include <stdlib.h> /* for exit() */ #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <stdio.h> #include <unistd.h> #include <string.h> /* memset() */ #include <sys/time.h> /* select() */ #define REMOTE_SERVER_PORT 1500 #define MAX_MSG 100 #define SOCKET_ERROR -1 int isReadable(int sd,int * error,int timeOut) { // milliseconds fd_set socketReadSet; FD_ZERO(&socketReadSet); FD_SET(sd,&socketReadSet); struct timeval tv; if (timeOut) { tv.tv_sec = timeOut / 1000; tv.tv_usec = (timeOut % 1000) * 1000; } else { tv.tv_sec = 0; tv.tv_usec = 0; } // if
NP Lab Manual , RNEC
Year : Semester:
2010
First
page: 62
if (select(sd+1,&socketReadSet,0,0,&tv) == SOCKET_ERROR) { *error = 1; return 0; } // if *error = 0; return FD_ISSET(sd,&socketReadSet) != 0; } /* isReadable */ /* END jcs 3/30/05 */ int main(int argc, char *argv[]) { int sd, rc, i, n, echoLen, flags, error, timeOut; struct sockaddr_in cliAddr, remoteServAddr, echoServAddr; struct hostent *h; char msg[MAX_MSG]; /* check command line args */ if(argc<3) { printf("usage : %s <server> <data1> ... <dataN> \n", argv[0]); exit(1); } /* get server IP address (no check if input is IP address or DNS name */ h = gethostbyname(argv[1]); if(h==NULL) { printf("%s: unknown host '%s' \n", argv[0], argv[1]); exit(1); } printf("%s: sending data to '%s' (IP : %s) \n", argv[0], h->h_name, inet_ntoa(*(struct in_addr *)h->h_addr_list[0])); remoteServAddr.sin_family = h->h_addrtype; memcpy((char *) &remoteServAddr.sin_addr.s_addr, h->h_addr_list[0], h->h_length); remoteServAddr.sin_port = htons(REMOTE_SERVER_PORT); /* socket creation */ sd = socket(AF_INET,SOCK_DGRAM,0);
NP Lab Manual , RNEC
page: 63
if(sd<0) { printf("%s: cannot open socket \n",argv[0]); exit(1); } /* bind any port */ cliAddr.sin_family = AF_INET; cliAddr.sin_addr.s_addr = htonl(INADDR_ANY); cliAddr.sin_port = htons(0); rc = bind(sd, (struct sockaddr *) &cliAddr, sizeof(cliAddr)); if(rc<0) { printf("%s: cannot bind port\n", argv[0]); exit(1); } /* BEGIN jcs 3/30/05 */ flags = 0; timeOut = 100; // ms /* END jcs 3/30/05 */ /* send data */ for(i=2;i<argc;i++) { rc = sendto(sd, argv[i], strlen(argv[i])+1, flags, (struct sockaddr *) &remoteServAddr, sizeof(remoteServAddr)); if(rc<0) { printf("%s: cannot send data %d \n",argv[0],i-1); close(sd); exit(1); } /* BEGIN jcs 3/30/05 */ /* init buffer */ memset(msg,0x0,MAX_MSG); while (!isReadable(sd,&error,timeOut)) printf("."); printf("\n"); /* receive echoed message */ echoLen = sizeof(echoServAddr); n = recvfrom(sd, msg, MAX_MSG, flags,
NP Lab Manual , RNEC
page: 64
(struct sockaddr *) &echoServAddr, &echoLen); if(n<0) { printf("%s: cannot receive data \n",argv[0]); continue; } /* print received message */ printf("%s: echo from %s:UDP%u : %s \n", argv[0],inet_ntoa(echoServAddr.sin_addr), ntohs(echoServAddr.sin_port),msg); /* END jcs 3/30/05 */ } return 1; } /* Compiling. $CC udp_str_clnt.c wrapsock.c -o udpstrclnt Execution.. $udpstrclnt <IP Address> data */
page: 65
Output: [student@localhost ~]$ cc udp_str_clnt.c wrapsock.c -o udpstrclnt [student@localhost ~]$./udpstrclnt 127.0.0.1 hai how are you udpstrclnt: sending data to 127.0.0.1 (IP:127.0.0.1) udpstrclnt : echo from 127.0.0.1 : UDP1500 : HAI udpstrclnt : echo from 127.0.0.1 : UDP1500 : HOW udpstrclnt : echo from 127.0.0.1 : UDP1500 : ARE udpstrclnt : echo from 127.0.0.1 : UDP1500 : YOU
page: 66