Advertisement
Guest User

Untitled

a guest
Apr 21st, 2018
129
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.98 KB | None | 0 0
  1. #include <sys/mman.h>
  2. #include <time.h>
  3. #include <stdio.h>
  4. #include <time.h>
  5. #include <sys/time.h>
  6. #include <stdlib.h>
  7. #include <stdint.h>
  8. #include <stdio.h>
  9. #include <sys/stat.h>
  10. #include <string.h>
  11. #include <fcntl.h>
  12. #include <unistd.h>
  13. #include <sys/wait.h>
  14. #include <sys/socket.h>
  15. #include <netdb.h>
  16. #include <netinet/in.h>
  17. #include <arpa/inet.h>
  18. #include <inttypes.h>
  19.  
  20. volatile int sum = 0;
  21.  
  22. int main(int argc, char *argv[]) {
  23.     int fd = socket(PF_INET, SOCK_STREAM, 0);
  24.     if (fd < 0) {
  25.         perror("socket");
  26.         return 1;
  27.     }
  28.  
  29.     // следующие два системных вызова предписывают освободить серверный порт
  30.     // немедленно по окончании работы процесса
  31.     int val = 1;
  32.     setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof(val));
  33.     setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &val, sizeof(val));
  34.  
  35.     // привязываем сокет к порту
  36.     // входящий адрес - любой
  37.     // номер порта - argv[1]
  38.     struct sockaddr_in s1;
  39.     s1.sin_family = AF_INET;
  40.     s1.sin_port = htons(strtol(argv[1], NULL, 10));
  41.     s1.sin_addr.s_addr = INADDR_ANY;
  42.     int r = bind(fd, (struct sockaddr*) &s1, sizeof(struct sockaddr_in));
  43.     if (r < 0) {
  44.         perror("bind");
  45.         return 1;
  46.     }
  47.  
  48.     // переключаем сокет в режим прослушивания
  49.     listen(fd, 5);
  50.  
  51.     while (1) {
  52.         // получаем новое подключение
  53.         struct sockaddr_in s2;
  54.         socklen_t slen = sizeof(s2); // обратие внимание, что именно socklen_t, не size_t!
  55.         int fd2 = accept(fd, (struct sockaddr*) &s2, &slen);
  56.         int tmp = read(fd2, &tmp, sizeof(tmp));
  57.         sum += tmp;
  58.         if (tmp == 0) {
  59.             close(fd2);
  60.             break;
  61.         }
  62.         close(fd2);
  63.     }
  64.     printf("%d\n", sum);
  65.     fflush(stdout);
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement