timeout_server.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. /*
  2. * Copyright (C) 2022 Amazon.com Inc. or its affiliates. All rights reserved.
  3. * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  4. */
  5. #include <arpa/inet.h>
  6. #include <stdio.h>
  7. #include <stdlib.h>
  8. #include <sys/time.h>
  9. #include <unistd.h>
  10. #ifdef __wasi__
  11. #include <wasi_socket_ext.h>
  12. #endif
  13. int
  14. main(int argc, char *argv[])
  15. {
  16. int socket_fd;
  17. int client_socket_fd;
  18. struct sockaddr_in addr = { 0 };
  19. int addrlen = sizeof(addr);
  20. int bool_opt = 1;
  21. addr.sin_family = AF_INET;
  22. addr.sin_port = htons(1234);
  23. addr.sin_addr.s_addr = htonl(INADDR_ANY);
  24. if ((socket_fd = socket(AF_INET, SOCK_STREAM, 0)) == -1) {
  25. perror("Create socket failed");
  26. return EXIT_FAILURE;
  27. }
  28. if (setsockopt(socket_fd, SOL_SOCKET, SO_REUSEADDR, &bool_opt,
  29. sizeof(bool_opt))
  30. == -1) {
  31. perror("Failed setting SO_REUSEADDR");
  32. goto fail;
  33. }
  34. if (bind(socket_fd, (struct sockaddr *)&addr, addrlen) == -1) {
  35. perror("Bind socket failed");
  36. goto fail;
  37. }
  38. if (listen(socket_fd, 1) == -1) {
  39. perror("Listen failed");
  40. goto fail;
  41. }
  42. if ((client_socket_fd =
  43. accept(socket_fd, (struct sockaddr *)&addr, (socklen_t *)&addrlen))
  44. == -1) {
  45. perror("Accept failed");
  46. goto fail;
  47. }
  48. printf("Client connected, sleeping for 10s\n");
  49. sleep(10);
  50. printf("Shuting down\n");
  51. shutdown(client_socket_fd, SHUT_RDWR);
  52. close(client_socket_fd);
  53. shutdown(socket_fd, SHUT_RDWR);
  54. close(socket_fd);
  55. return EXIT_SUCCESS;
  56. fail:
  57. close(socket_fd);
  58. return EXIT_FAILURE;
  59. }