Advertisement
Guest User

Untitled

a guest
Dec 18th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. #include <sys/types.h>
  2. #include <sys/socket.h>
  3. #include <sys/stat.h>
  4. #include <netinet/in.h>
  5. #include <stdio.h>
  6. #include <string.h>
  7. #include <fcntl.h>
  8. #include <unistd.h>
  9. enum { BACKLOG = 5 };
  10. int main(int argc, char **argv)
  11. {
  12. int sockfd;
  13. if ((sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
  14. return 0;
  15. }
  16. unsigned portnm;
  17. sscanf(argv[1], "%u", &portnm);
  18.  
  19. int val = 1;
  20. setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &val, sizeof val);
  21.  
  22. struct sockaddr_in own_addr;
  23. own_addr.sin_family = AF_INET;
  24. own_addr.sin_addr.s_addr = INADDR_ANY;
  25. own_addr.sin_port = htons(portnm);
  26.  
  27. if (bind(sockfd, (struct sockaddr *) &own_addr, sizeof own_addr) < 0) {
  28. return 0;
  29. }
  30. if (listen(sockfd, BACKLOG) < 0) {
  31. return 0;
  32. }
  33.  
  34. int32_t temp = 0, summ = 0;
  35.  
  36. do {
  37. struct sockaddr_in prt_adr;
  38. socklen_t party_len = sizeof prt_adr;
  39. int newsockfd;
  40. if ((newsockfd = accept(sockfd, (struct sockaddr*)&prt_adr, &party_len)) < 0) {
  41. return 0;
  42. }
  43. int32_t num;
  44. while (read(newsockfd, &num, sizeof num) > 0) {
  45. num = ntohl(num);
  46. summ += num;
  47. temp = num;
  48. if (!num) {
  49. break;
  50. }
  51. }
  52. } while (temp != 0);
  53. printf("%d\n", summ);
  54. shutdown(sockfd, SHUT_RDWR);
  55. close(sockfd);
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement