0

This is the code snippet (from beejus) where I am trying to create a process which will create a thread which will act as a Unix Domain Socket Server.

    void *domain_socket_cepki_server() {

    s = socket(AF_UNIX, SOCK_STREAM, 0);
    fprintf(stderr, "socket val is : %d\n", s);
    if (s == -1) {
       perror("socket");
       fprintf(stderr, "SOCKET ERROR: %d\n", s);
    }

    memset(&local, 0, sizeof(struct sockaddr_un));

    local.sun_family = AF_UNIX;
    strcpy(local.sun_path, SOCK_PATH);
    unlink(local.sun_path);
    //len = strlen(local.sun_path) + sizeof(local.sun_family);

    rc = bind(s, (struct sockaddr *) &local, sizeof(local));
    if (rc == -1) {
       perror("bind");
       fprintf(stderr, "bind failed %d : %s", errno, strerror(errno));
       exit(1);
    }

    if (listen(s, 5) == -1) {
       perror("listen");
       fprintf(stderr, "listen failed : %s", strerror(errno));
       exit(1);
    }

    int done, n;
    printf("Waiting for a connection...\n");
    t = sizeof(remote);
    if ((s2 = accept(s, (struct sockaddr *)&remote, &t)) == -1) {
        perror("accept");
        exit(1);
    }

    // send and recv code further.
    }

With this I am getting following error: bind: Invalid argument

bind() EINVAL says the following:

EINVAL The socket is already bound to an address.

EINVAL addrlen is wrong, or addr is not a valid address for this socket's domain.

What can go wrong in this bind() system call ?

  • What is the actual value of `SOCK_PATH`, and what is the actual be size of `local.sun_path` in your system? Have you read the [unix(7) man page](http://man7.org/linux/man-pages/man7/unix.7.html) yet? It talks about `sockaddr_un` and its relation to the `addrlen` parameter of `bind()` – Remy Lebeau May 13 '19 at 04:33
  • Thanks for quick reply!!! SOCK_PATH = /var/tmp where I have write permission. local.sun_path size is 104 and sockadd_un size is 106 (which is less than 108). – Ninja Security May 13 '19 at 05:02
  • do you get the same error if you set `addrlen` dynamically instead of using `sizeof()`? `rc = bind(s, (struct sockaddr *) &local, offsetof(struct sockaddr_un, sun_path) + strlen(SOCK_PATH) + 1);` – Remy Lebeau May 13 '19 at 06:41
  • Yes, thanks Remy, After changing the addrlen to offsetof(struct sockaddr_un, sun_path) + strlen(SOCK_PATH) , able to bind. Thanks again – Ninja Security May 13 '19 at 12:18

0 Answers0