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