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