如何在iOS中设置UNIX域插座



我正在尝试在iOS中设置一个unix域插座。根据https://iphonedevwiki.net/index.php/unix_sockets,这是我用来在服务器端设置套接字的代码:

    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: %dn", listenfd);
    // start the server
    int r = -1;
    while(r != 0) {
        r = bind(listenfd, (struct sockaddr*)&local, sizeof(local));
        printf("bind: %dn", 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: %dn", 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: %dn", 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
...

当我们返回-1时,我想知道我在代码中做错了什么时,看起来有问题吗?errno是1,是uperation_not_permittit

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

最新更新