How to create Unix Domain Socket with a specific permissions in C?

后端 未结 3 1910
一个人的身影
一个人的身影 2020-12-29 21:39

I have a simple code, like:

sockaddr_un address;
address.sun_family = AF_UNIX;
strcpy(address.sun_path, path);
unlink(path);

int fd = socket(AF_UNIX, SOCK_S         


        
3条回答
  •  抹茶落季
    2020-12-29 22:33

    I had the best luck using chmod() (NOT fchmod) using the file name for the unix domain socket after calling socket(), bind(), but, before calling listen().

      int return_value;
      const char *sock_path;
      struct sockaddr_un local;
    
      sock_path = "/tmp/mysocket";
    
      sockfd = socket(AF_UNIX, SOCK_STREAM, 0);
      if (sockfd == -1)
      {
        perror("socket");
        exit(-1);
      }
    
      local.sun_family = AF_UNIX; 
      strcpy(local.sun_path, sock_path);
      unlink(local.sun_path);
      len = strlen(local.sun_path) + sizeof(local.sun_family);
      bind(sockfd, (struct sockaddr *)&local, len);
    
      chmod(sock_path, 0777);
    
      retval = listen(sockfd, BACKLOG);
      if (retval == -1)
      {
        perror("listen");
        exit(-1);
      }
    

    . . . . .

提交回复
热议问题