Advertisement
anechka_ne_plach

Untitled

May 22nd, 2022
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.27 KB | None | 0 0
  1. ───────┼─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────
  2. 1 │ #include <sys/types.h>
  3. 2 │ #include <sys/socket.h>
  4. 2 │ #include <sys/socket.h>
  5. 3 │ #include <netdb.h>
  6. 4 │ #include <stdio.h>
  7. 5 │ #include <stdlib.h>
  8. 6 │ #include <netinet/in.h>
  9. 7 │ #include <arpa/inet.h>
  10. 8 │ #include <string.h>
  11. 9 │ #include <errno.h>
  12. 10 │ #include <signal.h>
  13. 11 │ #include <unistd.h>
  14. 12 │
  15. 13 │ void handler(int s) {
  16. 14 │ _exit(0);
  17. 15 │ }
  18. 16 │
  19. 17 │ int main(int argc, char* argv[]) {
  20. 18 │ if (argc != 4) {
  21. 19 │ return 1;
  22. 20 │ }
  23. 21 │ sigaction(SIGPIPE, &(struct sigaction) {.sa_handler=handler, .sa_flags=SA_RESTART }, NULL);
  24. 22 │
  25. 23 │ struct addrinfo hints = {
  26. 24 │ .ai_family = AF_INET,
  27. 25 │ .ai_socktype = SOCK_STREAM
  28. 26 │ };
  29. 27 │ struct addrinfo* result = NULL;
  30. 28 │ int err = getaddrinfo(argv[1], argv[2], &hints, &result);
  31. 29 │ if (err) {
  32. 30 │ fprintf(stderr, "error: %s\n", gai_strerror(err));
  33. 31 │ freeaddrinfo(result);
  34. 32 │ return 1;
  35. 33 │ }
  36. 34 │
  37. 35 │ int sfd;
  38. 36 │ if ((sfd = socket(PF_INET, SOCK_STREAM, 0)) < 0) {
  39. 37 │ fprintf(stderr, "socket error\n");
  40. 38 │ freeaddrinfo(result);
  41. 39 │ return 1;
  42. 40 │ }
  43. 41 │
  44. 42 │ if ((connect(sfd, result->ai_addr, result->ai_addrlen)) < 0) {
  45. 43 │ fprintf(stderr, "%s\n", strerror(errno));
  46. 44 │ freeaddrinfo(result);
  47. 45 │ return 1;
  48. 46 │ }
  49. 47 │ freeaddrinfo(result);
  50. 48 │
  51. 49 │ FILE* s_in = fdopen(dup(sfd), "r");
  52. 50 │ FILE* s_out = fdopen(sfd, "w");
  53. 51 │
  54. 52 │ if (fprintf(s_out, "%s\n", argv[3]) < 0 || fflush(s_out) < 0) {
  55. 53 │ fclose(s_in), fclose(s_out);
  56. 54 │ return 0;
  57. 55 │ }
  58. 56 │ int K = 0;
  59. 57 │ if (fscanf(s_in, "%d", &K) < 0) {
  60. 58 │ fclose(s_in), fclose(s_out);
  61. 59 │ return 0;
  62. 60 │ }
  63. 61 │ for (int i = 0; i <= K; ++i) {
  64. 62 │ if (fprintf(s_out, "%d\n", i) < 0) {
  65. 63 │ fclose(s_in), fclose(s_out);
  66. 64 │ return 0;
  67. 65 │ }
  68. 66 │ }
  69. 67 │ if (fflush(s_out) < 0) {
  70. 68 │ fclose(s_in), fclose(s_out);
  71. 69 │ return 0;
  72. 70 │ }
  73. 71 │ unsigned long long ans;
  74. 72 │ if (fscanf(s_in, "%llu", &ans) < 0) {
  75. 73 │ fclose(s_in), fclose(s_out);
  76. 74 │ return 0;
  77. 75 │ }
  78. 76 │ printf("%llu\n", ans);
  79. 77 │
  80. 78 │ fclose(s_in), fclose(s_out);
  81. 79 │ }
  82. ───────┴─────
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement