0

I have code:

#define SOCK_PATH "/Users/piotr/swigo.sock"

int ux_server_socket() {
    const int fd = socket(AF_UNIX, SOCK_STREAM, 0);
    if (fd == -1) {
        printf("%s\n", strerror(errno));
        return -1;
    }
    struct sockaddr_un addr;
    bzero(&addr, sizeof(addr));
    addr.sun_len = sizeof(addr);
    addr.sun_family = AF_UNIX;
    strcpy(addr.sun_path, SOCK_PATH);

    if (unlink(addr.sun_path) == -1) {
        printf("unlink: %s\n", strerror(errno));
    }

    int retv = bind(fd, (struct sockaddr*)&addr, (socklen_t)SUN_LEN(&addr));
    if (retv == -1) {
        printf("bind: %s\n", strerror(errno));
        return -1;
    }

    printf("valid socket: %d\n", fd);
    return fd;
}

When I create a project in C language in Xcode, this code works without any problems (in the console appears: valid socket: 3). However, when I create a project in Swift (Cocoa App), I added a C file to the project with this function (and the appropriate file h and bridge header too) something does not work. I see messages in the console:

unlink: Operation not permitted
bind: Address already in use

Why doesn't this valid C code work in a Swift project — any ideas?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
PiotrPsz
  • 1
  • 1
  • What are the permissions on the socket file? – zneak Feb 12 '18 at 23:12
  • permissions are: srwxr-xr-x, it is in my home directory, I have all the permissions – PiotrPsz Feb 12 '18 at 23:45
  • Since the unlink fails and the bind fails too, maybe the socket is still in use by a program that's still running, and that makes the code fail with 'Address already in use'? Find which process could have the socket in use. If all else fails, try a reboot, but it shouldn't be necessary. – Jonathan Leffler Feb 13 '18 at 01:23
  • Does Apple do any sandboxing that would explain it? Maybe try creating the socket in a location for temporary files instead. – Ove Feb 13 '18 at 09:12
  • @Ove location is not important, i did check tmp (and many others) directory too. But sandboxing? Yes, it is good idea, to check. – PiotrPsz Feb 13 '18 at 09:53
  • @Ove, it was the problem :) – PiotrPsz Feb 14 '18 at 10:45

1 Answers1

0

It was the problem with sandbox, the valid solution is idea of Ken Thomases in another task, i needed to set two checkboxes (App Sandbox, Network: Incoming Connections (Server) and Outgoing Connections (Client)):

screenshot of settings

see: Creating and binding socket on Mac OS Hight Sierra

melpomene
  • 84,125
  • 8
  • 85
  • 148
PiotrPsz
  • 1
  • 1