mercredi 29 avril 2020

How to create a unix socket file with read/write permissions for different users C++?

I have 2 different aplications running in 2 different users in linux. I want them to be connected by unix sockets and, as a unix domain socket is known by a pathname, the 2 applications need to share the same path and same the socket file that is created. The problem here is that when binding the socket in the Server, everything is fine but, when trying to connect from the 2nd application the error "access denied" appears.

Here is the code I am using for the server, who does create the socket file.

  int main() {
    struct sockaddr_un addr;
    char buf[100];
    int fd,cl,rc;

    if (argc > 1) socket_path=argv[1];

    if ( (fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) {
      perror("socket error");
      exit(-1);
    }

    memset(&addr, 0, sizeof(addr));
    addr.sun_family = AF_UNIX;
    if (*socket_path.c_str() == '\0') {
      *addr.sun_path = '\0';
      strncpy(addr.sun_path+1, socket_path.c_str()+1, sizeof(addr.sun_path)-2);
    } else {
      strncpy(addr.sun_path, socket_path.c_str(), sizeof(addr.sun_path)-1);
      unlink(socket_path.c_str());
    }

    if (bind(fd, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
      perror("bind error");
      exit(-1);
    }

    if (listen(fd, 5) == -1) {
      perror("listen error");
      exit(-1);
    }

     return 0;
}

Aucun commentaire:

Enregistrer un commentaire