Advertisement
Rainulf

tcp-server.c

Apr 18th, 2012
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.22 KB | None | 0 0
  1. #include <ctype.h>
  2. #include <sys/types.h>
  3. #include <sys/socket.h>
  4. #include <netinet/in.h>
  5. #include <signal.h>
  6.  
  7. #define SIZE sizeof(struct sockaddr_in)
  8. #define MYPORT 7091
  9. void catcher(int sig);
  10. int newsockfd;
  11.  
  12. main()
  13. {
  14.    int sockfd;
  15.    char c;
  16.    struct sockaddr_in server = {AF_INET, MYPORT, INADDR_ANY};
  17.    static struct sigaction act;
  18.  
  19.    act.sa_handler = catcher;
  20.    sigfillset(&(act.sa_mask));
  21.    sigaction(SIGPIPE, &act, NULL);
  22.  
  23.    if((sockfd=socket(AF_INET, SOCK_STREAM, 0)) == -1){
  24.       perror("socket call failed");
  25.       exit(1);
  26.    }
  27.    if(bind(sockfd, (struct sockaddr *)&server, SIZE) == -1){
  28.       perror("bind call failed");
  29.       exit(1);
  30.    }
  31.    if(listen(sockfd,5) == -1){
  32.       perror("listen call failed");
  33.       exit(1);
  34.    }
  35.    while(1){
  36.       if((newsockfd=accept(sockfd, NULL, NULL)) == -1){
  37.          perror("accept call failed");
  38.          continue;
  39.       }
  40.      
  41.       if(fork() == 0){
  42.          while(recv(newsockfd, &c, 1, 0) > 0){
  43.             c = toupper(c);
  44.             send(newsockfd, &c, 1, 0);
  45.          }
  46.          close(newsockfd);
  47.          exit(0);
  48.       }
  49.      
  50.       close(newsockfd);
  51.    }
  52. }
  53.  
  54. void catcher(int sig)
  55. {
  56.    close(newsockfd);
  57.    exit(0);
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement