echo_server.c

Go to the documentation of this file.
00001 /*
00002  * Copyright 2002 Sony Corporation 
00003  *
00004  * Permission to use, copy, modify, and redistribute this software for
00005  * non-commercial use is hereby granted.
00006  *
00007  * This software is provided "as is" without warranty of any kind,
00008  * either expressed or implied, including but not limited to the
00009  * implied warranties of fitness for a particular purpose.
00010  */
00011 
00012 #include <stdio.h>
00013 #include <string.h>
00014 #include <signal.h>
00015 #include <sys/types.h>
00016 #include <sys/socket.h>
00017 #include <netinet/in.h>
00018 
00019 #define PORT     54321
00020 #define BUFSIZE  512
00021 
00022 int sock = -1;
00023 int fd = -1;
00024 
00025 void sigint_handler()
00026 {
00027     fprintf(stderr, "sigint_handler()\n");
00028 
00029     if (sock >= 0) close(sock);
00030     if (fd >= 0) close(fd);
00031     exit(1);
00032 }
00033 
00034 void accept_and_echo()
00035 {
00036     struct sockaddr_in  caddr;
00037     int  len, ret, wsize;
00038     char buf[BUFSIZE];
00039 
00040     len = sizeof(caddr);
00041     fd = accept(sock, (struct sockaddr *)&caddr, &len);
00042     if (fd < 0) {
00043         perror("accept");
00044         close(sock);
00045         exit(1);
00046     }
00047 
00048     ret = read(fd, buf, BUFSIZE);
00049     if (ret == -1) {
00050         perror("read");
00051         close(fd); fd = -1;
00052         return;
00053     }
00054     wsize = ret;
00055     
00056     while (1) {
00057 
00058         ret = write(fd, buf, wsize);
00059         if (ret != wsize) {
00060             perror("write");
00061             close(fd); fd = -1;
00062             return;
00063         }
00064 
00065         ret = read(fd, buf, BUFSIZE);
00066         if (ret == -1) {
00067             perror("read");
00068             close(fd); fd = -1;
00069             return;
00070         }
00071         wsize = ret;
00072     }
00073 }
00074 
00075 main()
00076 {
00077     int    i;
00078     struct sockaddr_in  saddr;
00079 
00080     signal(SIGINT, sigint_handler);
00081     
00082     if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
00083         perror("socket");
00084         exit(1);
00085     }
00086 
00087     memset((void*)&saddr, 0, sizeof(saddr));
00088     saddr.sin_family = AF_INET;
00089     saddr.sin_addr.s_addr = INADDR_ANY;
00090     saddr.sin_port = htons(PORT);
00091 
00092     if (bind(sock, (struct sockaddr *)&saddr, sizeof(saddr)) < 0){
00093         perror("bind");
00094         close(sock);
00095         exit(1);
00096     }
00097 
00098     if (listen(sock, 1) < 0) {
00099         perror("listen");
00100         close(sock);
00101         exit(1);
00102     }
00103 
00104     while (1) {
00105         accept_and_echo();
00106     }
00107 }

Generated on Sun Dec 2 23:04:28 2007 for openSDK by  doxygen 1.3.9.1