Advertisement
anechka_ne_plach

Untitled

May 23rd, 2022
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.22 KB | None | 0 0
  1. 1 │ #include <sys/types.h>
  2. 2 │ #include <sys/socket.h>
  3. 3 │ #include <netdb.h>
  4. 1 │ #include <sys/types.h>
  5. 2 │ #include <sys/socket.h>
  6. 3 │ #include <netdb.h>
  7. 4 │ #include <stdio.h>
  8. 5 │ #include <stdlib.h>
  9. 6 │ #include <netinet/in.h>
  10. 7 │ #include <netdb.h>
  11. 8 │ #include <arpa/inet.h>
  12. 9 │ #include <string.h>
  13. 10 │ #include <errno.h>
  14. 11 │ #include <signal.h>
  15. 12 │ #include <unistd.h>
  16. 13 │
  17. 14 │ int main(int argc, char* argv[]) {
  18. 15 │ if (argc != 2) {
  19. 16 │ return 1;
  20. 17 │ }
  21. 18 │
  22. 19 │ int sfd;
  23. 20 │ if ((sfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
  24. 21 │ perror("socket");
  25. 22 │ return 1;
  26. 23 │ }
  27. 24 │
  28. 25 │ int sopt = 1;
  29. 26 │ if (setsockopt(sfd, SOL_SOCKET, SO_REUSEADDR, &sopt, sizeof(sopt)) < 0) {
  30. 27 │ perror("setsockopt");
  31. 28 │ return 1;
  32. 29 │ }
  33. 30 │
  34. 31 │ struct sockaddr_in addr;
  35. 32 │ addr.sin_family = AF_INET;
  36. 33 │ addr.sin_port = htons(strtol(argv[1], NULL, 10));
  37. 34 │ addr.sin_addr.s_addr = INADDR_ANY;
  38. 35 │
  39. 36 │ if (bind(sfd, (struct sockaddr*)&addr, sizeof(addr)) < 0) {
  40. 37 │ perror("bind");
  41. 38 │ return 1;
  42. 39 │ }
  43. 40 │
  44. 41 │ if (listen(sfd, 5) < 0) {
  45. 42 │ perror("listen");
  46. 43 │ return 1;
  47. 44 │ }
  48. 45 │
  49. 46 │ int sum = 0, val = -1;
  50. 47 │ while (val != 0) {
  51. 48 │ struct sockaddr_in new_addr;
  52. 49 │ socklen_t new_len = sizeof(struct sockaddr_in);
  53. 50 │ int afd = accept(sfd, (struct sockaddr*)&new_addr, &new_len);
  54. 51 │ char buf[sizeof(int)];
  55. 52 │ int it = 0;
  56. 53 │ while (it < sizeof(int)) {
  57. 54 │ it += read(afd, buf + it, sizeof(int) - it);
  58. 55 │ }
  59. 56 │ val = ntohl(*(int*)buf);
  60. 57 │ sum += val;
  61. 58 │ close(afd);
  62. 59 │ }
  63. 60 │ printf("%d\n", sum);
  64. 61 │ close(sfd);
  65. 62 │ }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement