Advertisement
Guest User

Untitled

a guest
May 22nd, 2015
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.00 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <sys/types.h>
  3. #include <netinet/in.h>
  4. #include <sys/socket.h>
  5. #include <netdb.h>
  6. #include <sys/time.h>
  7. #include <unistd.h>
  8. #include <stdlib.h>
  9. #include <errno.h>
  10.  
  11. #define PORT        3452
  12. #define BUFLEN      1024
  13.  
  14. void main()
  15. {
  16.     int i;
  17.     int rc;
  18.     int s;
  19.     int cs;
  20.     char buf[BUFLEN+1];
  21.     struct sockaddr_in  sa;
  22.     struct sockaddr_in  csa;
  23.     int size_csa;
  24.     fd_set rfd;
  25.     fd_set c_rfd;
  26.     int dsize;
  27.  
  28.     memset(&sa, 0, sizeof(sa));
  29.     sa.sin_family = AF_INET;
  30.     sa.sin_port = htons(PORT);
  31.     sa.sin_addr.s_addr = INADDR_ANY;
  32.  
  33.     s = socket(AF_INET, SOCK_STREAM, 0);
  34.     if (s < 0) {
  35.         perror("socket: allocation failed");
  36.         exit(EXIT_FAILURE);
  37.     }
  38.  
  39.     int option = 1;
  40.     if (setsockopt(s, SOL_SOCKET, SO_REUSEADDR, &option, sizeof(option)) < 0)
  41.     {
  42.         perror("Setsockopt");
  43.         exit(EXIT_FAILURE);
  44.     }
  45.  
  46.     rc = bind(s, (struct sockaddr *)&sa, sizeof(sa));
  47.  
  48.     if (rc) {
  49.         perror("bind");
  50.         exit(EXIT_FAILURE);
  51.     }
  52.  
  53.     rc = listen(s, 5);
  54.  
  55.     if (rc) {
  56.         perror("listen");
  57.         exit(EXIT_FAILURE);
  58.     }
  59.  
  60.     size_csa = sizeof(csa);
  61.  
  62.     dsize = getdtablesize();
  63.  
  64.     FD_ZERO(&rfd);
  65.     FD_SET(s, &rfd);
  66.  
  67.     while (1){
  68.         c_rfd = rfd;
  69.         rc = select(dsize, &c_rfd, NULL, NULL, (struct timeval *)NULL);
  70.  
  71.         if (FD_ISSET(s, &c_rfd)) {
  72.                 cs = accept(s, (struct sockaddr *)&csa, &size_csa);
  73.  
  74.                 if (cs < 0){
  75.                     continue;
  76.                 }
  77.  
  78.             FD_SET(cs, &rfd);
  79.  
  80.             continue;
  81.         }
  82.  
  83.         for (i = 0; i < dsize; i++){
  84.             if (i != s && FD_ISSET(i, &c_rfd)) {
  85.                 rc = read(i, buf, BUFLEN);
  86.                 printf("%s", buf);
  87.                 if (rc == 0) {
  88.                     close(i);
  89.                     FD_CLR(i, &rfd);
  90.                 }
  91.                 else {
  92.                     printf("%s", buf);
  93.                 }
  94.             }
  95.         }
  96.     }
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement