選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

67 行
1.7 KiB

  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <stdlib.h>
  4. #include <time.h>
  5. #include <sys/socket.h>
  6. #include <sys/types.h>
  7. #include <netdb.h>
  8. #include <arpa/inet.h>
  9. #include <unistd.h>
  10. #define SERVER_IP_ADDR "127.0.0.1"
  11. #define SERVER_PORT "2000"
  12. #define SECRET_NUMBER 42
  13. int main() {
  14. int status;
  15. struct addrinfo hints;
  16. struct addrinfo *servinfo;
  17. struct sockaddr_storage client_addr;
  18. socklen_t addrlen = sizeof client_addr;
  19. memset(&hints, 0, sizeof hints);
  20. hints.ai_family = AF_UNSPEC;
  21. hints.ai_socktype = SOCK_DGRAM;
  22. if ((status = getaddrinfo(SERVER_IP_ADDR, SERVER_PORT, &hints, &servinfo)) != 0) {
  23. fprintf(stderr, "getaddrinfo error: %s\n", gai_strerror(status));
  24. exit(1);
  25. }
  26. int s = socket(servinfo->ai_family, servinfo->ai_socktype, servinfo->ai_protocol);
  27. int l = 1, r = SECRET_NUMBER+1;
  28. while (l < r) {
  29. int m = l + (r - l) / 2;
  30. char str[32];
  31. sprintf(str, "%d", m);
  32. sendto(s, str, 32, 0, servinfo->ai_addr, servinfo->ai_addrlen);
  33. char res[32];
  34. memset(res, 0, 32);
  35. if (recvfrom(s, res, 32, 0,
  36. (struct sockaddr *)&client_addr, &addrlen) < 0) {
  37. printf("Failed to receive a message from client\n");
  38. }
  39. printf("res: %s\n", res);
  40. if (strcmp(res, "LESS\0") == 0)
  41. l = m;
  42. else if (strcmp(res, "MORE\0") == 0)
  43. r = m;
  44. else if (strcmp(res, "WIN\0") == 0) {
  45. close(s);
  46. freeaddrinfo(servinfo);
  47. printf("Secret Number: %s\n", str);
  48. exit(0);
  49. } else {
  50. fprintf(stderr, "unexpected error: %s\n", res);
  51. exit(1);
  52. }
  53. }
  54. close(s);
  55. freeaddrinfo(servinfo);
  56. }