client_non_blocking.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <unistd.h>
  4. #include <fcntl.h>
  5. #include <sys/socket.h>
  6. #include <netinet/in.h>
  7. #include <arpa/inet.h>
  8. #include <errno.h>
  9. #include <string.h>
  10. #include <sys/select.h>
  11. #define SERVER_HOST "127.0.0.1"
  12. #define SERVER_PORT 12345
  13. int main()
  14. {
  15. int sockfd;
  16. struct sockaddr_in server_addr;
  17. fd_set write_fds;
  18. struct timeval timeout;
  19. int flags, result;
  20. sockfd = socket(AF_INET, SOCK_STREAM, 0);
  21. if (sockfd == -1)
  22. {
  23. perror("socket");
  24. return 1;
  25. }
  26. memset(&server_addr, 0, sizeof(server_addr));
  27. server_addr.sin_family = AF_INET;
  28. server_addr.sin_port = htons(SERVER_PORT);
  29. if (inet_pton(AF_INET, SERVER_HOST, &server_addr.sin_addr) <= 0)
  30. {
  31. perror("inet_pton");
  32. close(sockfd);
  33. return 1;
  34. }
  35. flags = fcntl(sockfd, F_GETFL, 0);
  36. if (flags == -1)
  37. {
  38. perror("fcntl");
  39. close(sockfd);
  40. return 1;
  41. }
  42. if (fcntl(sockfd, F_SETFL, flags | O_NONBLOCK) == -1)
  43. {
  44. perror("fcntl");
  45. close(sockfd);
  46. return 1;
  47. }
  48. result = connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
  49. if (result < 0 && errno != EINPROGRESS)
  50. {
  51. perror("connect");
  52. close(sockfd);
  53. return 1;
  54. }
  55. printf("Trying to connect...\n");
  56. while (1)
  57. {
  58. FD_ZERO(&write_fds);
  59. // FD_SET(sockfd, &write_fds);
  60. timeout.tv_sec = 0;
  61. timeout.tv_usec = 100000;
  62. result = select(sockfd + 1, NULL, &write_fds, NULL, &timeout);
  63. if (result == -1)
  64. {
  65. perror("select");
  66. close(sockfd);
  67. return 1;
  68. }
  69. if (FD_ISSET(sockfd, &write_fds))
  70. {
  71. printf("Successfully connected to %s:%d\n", SERVER_HOST, SERVER_PORT);
  72. break;
  73. }
  74. else
  75. {
  76. printf("Still attempting to connect...\n");
  77. sleep(1); }
  78. }
  79. close(sockfd);
  80. return 0;
  81. }