Windows WSL 上的 Linux 中的 AF_UNIX 套接字无法绑定到 /mnt 文件:错误 95,不支持操作

Ina*_*tua 2 linux bind unix-socket windows-subsystem-for-linux wsl-2

我们需要将 Windows 客户端应用程序连接到 Linux 服务器应用程序。Linux 端在 Windows 10 (10.0.19044) 中的 WSL2 之上运行。

我们想要使用 UNIX 域套接字,并遵循https://devblogs.microsoft.com/commandline/windowswsl-interop-with-af_unix/中的指导

服务器程序成功绑定到“本地”文件系统中的文件(例如/tmp/mysock),但无法绑定到已安装驱动器中的“Windows 端”文件(例如/mnt/c/mysock) ,这是服务器可以接受来自 Windows 端 AF_UNIX 套接字的连接所必需的。

我得到的 errno 是 95 :“不支持操作”我尝试使用 sudo 运行,但结果相同。

知道发生了什么事吗?

服务器代码是:

#include <sys/socket.h>
#include <sys/un.h>

#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <unistd.h>
#include <errno.h>

#undef NDEBUG

// filename comes as command-line argument
int main(int argc, char *argv[])
{
    struct sockaddr_un addr;
    int ret = -1;
    
    printf("Starting NVC_LINUX...\n");
    
    assert(argc == 2);
    char *filename = argv[1];
    
    int sfd = socket(AF_UNIX, SOCK_STREAM, 0);
    assert(sfd != -1);

    // Delete any file that already exists at the address. Make sure the deletion
    // succeeds. If the error is just that the file/directory doesn't exist, it's fine.
    ret = remove(filename);
    assert(ret != -1 || errno == ENOENT);

    // Zero out the address, and set family and path.
    memset(&addr, 0, sizeof(struct sockaddr_un));
    addr.sun_family = AF_UNIX;
    assert(strlen(filename) <= sizeof(addr.sun_path) - 1);
    strncpy(addr.sun_path, filename, sizeof(addr.sun_path) - 1);

    ret = bind(sfd, (struct sockaddr *) &addr, sizeof(struct sockaddr_un));
    if (ret == -1) printf("errno : %d - %s\n", errno, strerror(errno));
    assert(ret != -1);

    ret = listen(sfd, 1);
    assert(ret != -1);

    printf("Waiting to accept a connection...\n");
    // NOTE: blocks until a connection request arrives.
    int cfd = accept(sfd, NULL, NULL);
    assert(cfd != -1);
    printf("Accepted socket fd = %d\n", cfd);

    char cmd;
    char res[32];
    while (1)
    {
        // get char from Win side
        ssize_t num_read = read(cfd, (void *) &cmd, sizeof(cmd));
        assert(num_read == sizeof(cmd));

        printf("  cmd=%c\n", cmd);
        
        // generate reply
        sprintf(res, "Hello from Linux, %c\n", cmd);

        // send data
        ssize_t num_written = write(cfd, (const void *) res, sizeof(res));
        assert(num_written == sizeof(res));
    }

    (void) close(cfd);
    (void) close(sfd);

    printf("done.\n");
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

Not*_*1ds 5

很巧的是,我昨天在WSL GitHub 问题上搜索有关 X11 套接字的信息时,遇到了这个关于AF_UNIXWSL2 支持的问题(与我的主题无关,但与您的主题相关),这引起了我的注意眼睛只是因为它最近被设计为关闭。

简而言之,AF_UNIX目前 WSL2 不支持。如果您的应用程序可能,请考虑将 WSL 发行版转换(或复制)到 WSL1,其中AF_UNIX受支持的 WSL1。

或者,您可以在 Windows 和 Linux 端之间使用网络连接。