bind-local-socket-to-symlink.cpp 665 B

12345678910111213141516171819202122232425262728293031
  1. #include <stdio.h>
  2. #include <string.h>
  3. #include <sys/socket.h>
  4. #include <unistd.h>
  5. int main(int, char**)
  6. {
  7. constexpr const char* path = "/tmp/foo";
  8. int rc = symlink("bar", path);
  9. if (rc < 0) {
  10. perror("symlink");
  11. return 1;
  12. }
  13. int fd = socket(AF_UNIX, SOCK_STREAM, 0);
  14. if (fd < 0) {
  15. perror("socket");
  16. return 1;
  17. }
  18. struct sockaddr_un addr;
  19. memset(&addr, 0, sizeof(addr));
  20. addr.sun_family = AF_UNIX;
  21. strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
  22. rc = bind(fd, (struct sockaddr*)(&addr), sizeof(addr));
  23. if (rc < 0 && errno == EADDRINUSE)
  24. return 0;
  25. return 1;
  26. }