You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
1.8 KiB

2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
2 months ago
  1. #include <errno.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <sys/socket.h>
  6. #include <sys/un.h>
  7. #include <unistd.h>
  8. #define SOCKET_PATH "/tmp/unix_dgram_demo"
  9. int main() {
  10. int sock_fd;
  11. struct sockaddr_un server_addr, client_addr;
  12. socklen_t client_len;
  13. char buffer[10240];
  14. // Create socket
  15. sock_fd = socket(AF_UNIX, SOCK_DGRAM, 0);
  16. if (sock_fd == -1) {
  17. perror("socket");
  18. exit(EXIT_FAILURE);
  19. }
  20. // Remove socket file if it already exists
  21. unlink(SOCKET_PATH);
  22. // Configure server address
  23. memset(&server_addr, 0, sizeof(server_addr));
  24. server_addr.sun_family = AF_UNIX;
  25. strncpy(server_addr.sun_path, SOCKET_PATH, sizeof(server_addr.sun_path) - 1);
  26. // Bind socket to address
  27. if (bind(sock_fd, (struct sockaddr *)&server_addr, sizeof(server_addr)) == -1) {
  28. perror("bind");
  29. close(sock_fd);
  30. exit(EXIT_FAILURE);
  31. }
  32. // 设置超时时间为5秒
  33. struct timeval tv;
  34. tv.tv_sec = 1; // 秒
  35. tv.tv_usec = 0; // 微秒
  36. // 设置SO_RCVTIMEO选项
  37. if (setsockopt(sock_fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)) < 0) {
  38. perror("setsockopt failed");
  39. return -1;
  40. }
  41. printf("Receiver is waiting for messages on %s...\n", SOCKET_PATH);
  42. while (1) {
  43. // Receive message
  44. client_len = sizeof(client_addr);
  45. ssize_t num_bytes = recvfrom(sock_fd, buffer, sizeof(buffer) - 1, 0, (struct sockaddr *)&client_addr, &client_len);
  46. if (num_bytes == -1) {
  47. if (errno == EAGAIN || errno == EWOULDBLOCK) { // 超时错误
  48. printf("No message received within the timeout period.\n");
  49. continue;
  50. }
  51. perror("!!!recvfrom");
  52. exit(EXIT_FAILURE);
  53. } else {
  54. buffer[num_bytes] = '\0';
  55. printf("Received message: %d\n", num_bytes);
  56. }
  57. }
  58. // Clean up
  59. close(sock_fd);
  60. unlink(SOCKET_PATH);
  61. return 0;
  62. }