如何在iOS中设置UNIX域套接字?

时间:2019-05-14 15:54:40

标签: ios ipc unix-socket

我正在尝试在iOS中设置UNIX域套接字。根据{{​​3}},这是我用来在服务器端设置套接​​字的代码:

    const char *socket_path = "/var/run/myserver.socket";
    // setup socket
    struct sockaddr_un local;
    strcpy(local.sun_path, socket_path);
    unlink(local.sun_path);
    local.sun_family = AF_UNIX;
    int listenfd = socket(AF_UNIX, SOCK_STREAM, 0);
    printf("listenfd: %d\n", listenfd);
    // start the server
    int r = -1;
    while(r != 0) {
        r = bind(listenfd, (struct sockaddr*)&local, sizeof(local));
        printf("bind: %d\n", r);
        usleep(200 * 1000);
    }
    int one = 1;
    setsockopt(listenfd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof(one));
    // start listening for new connections
    r = -1;
    while(r != 0) {
        r = listen(listenfd, 20);
        printf("listen: %d\n", r);
        usleep(200 * 1000);
    }
    // wait for new connection, and then process it
    int connfd = -1;
    while(true) {
        if(connfd == -1) {
            // wait for new connection
            connfd = accept(listenfd, (struct sockaddr*)NULL, NULL);
            printf("new connfd: %d\n", connfd);
        }
        // process incoming data
        char buffer[4096];
        int len = recv(connfd, buffer, sizeof(buffer), 0);
        if(len == 0) {
            printf("connfd %d disconnected!\n", connfd);
            connfd = -1;
            continue;
        } else {
            printf("connfd %d recieved data: %s", connfd, buffer);
            // send some data back (optional)
            const char *response = "got it!\n";
            send(connfd, response, strlen(response) + 1, 0);
        }
    }

但是,当我在iPhone上运行此代码时,却在控制台中找到了它:

listenfd: 3
bind: -1
bind: -1
bind: -1
bind: -1
bind: -1
...

当我们做bind()时返回-1时似乎有问题,我想知道我在代码中做错了什么吗? errno为1,即OPERATION_NOT_PERMITTED

1 个答案:

答案 0 :(得分:0)

不允许在iOS上的/ var / run中创建对象。您需要将套接字放在允许创建对象的目录中,例如FileManager.shared.temporaryDirectory